0

I'm trying to use a for loop to iterate through the first element of a list of tuples.

for i in link_list:
    print 'http://www.newyorksocialdiary.com%s' % link_list[i][0]

However, I get this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-72-8c0e1be937a4> in <module>()
      1 for i in link_list:
----> 2     print 'http://www.newyorksocialdiary.com%s' % link_list[i][0]

TypeError: list indices must be integers, not tuple

How can I iterate through the list of tuples and print only the first element, such as:

'http://www.newyorksocialdiary.com/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up'
'http://www.newyorksocialdiary.com/party-pictures/2014/gala-guests'

If it helps, this is what link_list looks like:

[('/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up',
  datetime.datetime(2014, 12, 1, 0, 0)),
 ('/party-pictures/2014/gala-guests', datetime.datetime(2014, 11, 24, 0, 0)),
 ('/party-pictures/2014/equal-justice', datetime.datetime(2014, 11, 20, 0, 0)),
 ('/party-pictures/2014/celebrating-the-treasures',
  datetime.datetime(2014, 11, 18, 0, 0)),
 ('/party-pictures/2014/associates-and-friends',
  datetime.datetime(2014, 11, 17, 0, 0))]
4
  • 3
    Use % i[0] because for loops by default iterate over the container elements, not the indices. Commented Jan 6, 2018 at 20:48
  • It looks like your link list contains tuples... Something like link_list = [(1, "foo"), (2, "bar")...] Also, keep in mind that when you do for i in list(), you get (in i) items in the list, not indexes (maybe you wanted to do something like for i in range(len(link_list))? Commented Jan 6, 2018 at 20:50
  • I ran into some lag, so some of the post wasn't posted. finishing the writing of it now. Commented Jan 6, 2018 at 20:50
  • Does this answer your question? TypeError: list indices must be integers, not str - iterating list Commented Jun 6, 2022 at 11:11

2 Answers 2

1

You've misunderstood the way for loops work in Python. i is not an index, it's the element itself. You should use % i[0].

Sign up to request clarification or add additional context in comments.

2 Comments

wow, im completely overlooked it. thank you! selected for answer because it was answered first.
there's a 3 minute delay. i just logged back in. thanks for the kind reminder.
0

You can do either:

for i in link_list:
    print 'http://www.newyorksocialdiary.com%s' % i[0]

or if you need the actual index for some other reason:

for i in range(len(link_list)):
    print 'http://www.newyorksocialdiary.com%s' % link_list[i][0]

When you do for i in link_list, i is an element of the list, not the index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.