iterate over list with indexes but each index shoud represent single item

Question:

I want to find out how to iterate over list with indexes but each index should represent single item (not character in item). I have list = ['one', 'two', 'three', 'four'] and I want to get each item like this:

list[0] = 'one'
list[1] = 'two'
list[3] = 'four'

How can I do it with python?

Asked By: rastr__

||

Answers:

You should avoid indexing lists like this, it isn’t a pythonic way of doing it and looks ugly, but if you really want to then you can do it as follows:

l = ['one', 'two', 'three', 'four']
for i in range(len(l)):
 print(l[i])

# or
for i, v in enumerate(l):
 print(v, l[i])

enumerate() is very useful when you need to skip certain indexes of a list or something, but maintain the python list iteration method

In reply to comment (now deleted), "How would I most pythonically iterate a list and only include certain elements based on conditions such as index number and values of nearby elements?":

To skip certain indexes I would use enumerate as above, such as:

l = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']
for i, v in enumerate(l):
 if i > 1 and (i % 3) == 0:
  print(v, l[i])

iterating a list to be able to compare to elements nearby is a case where it has to look a bit messy, granted, so either using enumerate like above or you can use zip and slices,

l = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']
for i, v in enumerate(l):
 if i > 0 and l[i - 1][0] in v:
  print(i, v)

# slice method
for x, y in zip(l, l[1:]):
 if x[0] in y:
  print(y)

# or if you still need the index you can combine enumerate and zip like this
for i, (x, y) in enumerate(zip(l, l[1:])):
 if x[0] in y:
  print(i, y)

note that "x" starts at element 0 and "y" starts at element 1 in the slicing method so the indexes printed by the enumerate() and enumerate(zip()) methods don’t match, you would need to add 1 to i in the latter

Answered By: G.S
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.