Looping Over a List in Python

Iterating over a list in python using for-loop

When you do for i in row, i takes the values in row, i.e. '1', then '2', then '3'.

Those are strings, which are not valid as a list index. A list index should be an integer. When doing range(len(row)) you loop on integers up to the size of the list.

By the way, a better approach is:

for elt_id, elt in enumerate(list):
# do stuff

Accessing the index in 'for' loops

Use the built-in function enumerate():

for idx, x in enumerate(xs):
print(idx, x)

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.

Check out PEP 279 for more.

How can I iterate over a list of lists?

You've already been given the answer in the comments. But to understand why your code doesn't work in its current state, take a look at this:

>>> xs = [[1.,2.,3.], [4.,5.,6.], [7.,8.,9.]]
>>> for i in xs:
... print(i)
...
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]

The for loop iterates over the elements, not the indices. The variable i is probably confusing here. Anyway, inside the loop, i will contain a sublist at each iteration. So xs[i] is an invalid operation here -- you may only provide integers as indices to a python list.

If you want to get the first and last element of each sublist, all you've got to do is print out i[0] and i[-1].

On a related note, you can iterate over the indices using the range function:

 for i in range(len(xs)):
print(xs[i][0], xs[i][-1])

But this is not recommended, since it is more efficient to just iterate over the elements directly, especially for this use case.

You can also also use enumerate, if you need both:

 for c, i in enumerate(xs):
print(i[0], xs[c][-1]) # both work here

Iterate over a list based on list with set of iteration steps

This works:

l = [6,2,2,5,2,5,1,7,9,4]
w = [2,2,1,1]
k = 1

def take(xs, runs, skip_size):
ixs = iter(xs)
for run_size in runs:
for _ in range(run_size ):
yield next(ixs)
for _ in range(skip_size):
next(ixs)

result = list(take(l, w, k))
print(result)

Result:

[6, 2, 5, 2, 1, 9]

The function is what's called a generator, yielding one part of the result at a time, which is why it's combined into a list with list(take(l, w, k)).

Inside the function, the list xs that is passed in is wrapped in an iterator, to be able to take one item at a time with next().

runs defines how many items to take and yield, skip_size defines how many items to skip to skip after each 'run'.

As a bonus, here's a fun one-liner - if you can figure out why it works, I think you know enough about the problem to move on :)

[y for i, y in zip([x for xs in [[1] * aw + [0] * k for aw in w] for x in xs], l) if i]

How to iterate over a list in chunks

Modified from the Recipes section of Python's itertools docs:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)

Example

grouper('ABCDEFG', 3, 'x')  # --> 'ABC' 'DEF' 'Gxx'

Note: on Python 2 use izip_longest instead of zip_longest.

Iterating through list of list in Python

This traverse generator function can be used to iterate over all the values:

def traverse(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
for subvalue in traverse(value, tree_types):
yield subvalue
else:
yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

Iterate over multiple lists simultaneously in python

The zip function gives you the elements in pairs.

for (a, b, c), (d, e, f) in zip(elem1, elem2):
do something...

You could also do it with indexes

for i in range(len(elem1)):
(a, b, c), (d, e, f) = elem1[i], elem2[i]
do something...


Related Topics



Leave a reply



Submit