How To Iterate Through A List In Python

For a Python list or tuple object, we can go through it via a for loop, which we call iteration. In Python, iteration is done by for... in, whereas in many languages, such as C, iteration lists are done by subscripts, such as below Java code.

// Java loop in a list example.
for (i=0; i<list.length; i++) {
    n = list[i];
    println(n);
}
# below are Python example to loop through a list object 
l = ['a', 'b', 'c']
for item in l:
   print(item)
a
b
c

 

As you can see, Python’s for loop is more abstract than C’s for loop, because Python’s for loop can be applied to other iterable objects as well as lists or tuples. List data type has subscripts, but many other data types do not have subscripts. However, as long as it is an iterable object, it can be iterated with or without subscripts. For example, Python dict object can be iterated also as below:

>>> d = {'c++': 1, 'java': 2, 'python': 3}
>>> for key in d:
...     print(key)
...
c++
java
python

Because Python dict use different method to store data than the way of list sequence, so the iterative results may not be the same as the order is. By default, dict iterates for the key. If you want to iterate value, you can use for value in d.values(), if you want to iterate both key and value, you can use for k, v in d.items().

Because strings are also iterable objects, then you can use for loops on string also.

>>> for ch in 'Python':
...     print(ch)
...
P
y
t
h
o
n

So, when we use a for loop, the for loop works fine as long as we’re working on an iterable object, and we don’t really care if that object is a list or some other data type. So, how to check whether an object is an iterable object or not? The method is to check if the object is an instance of Iterable class type of collections module.

>>> from collections import Iterable # first import Iterable class from collections module.
>>> isinstance('code-learner.com', Iterable) # use isinstance function to check string data.
True
>>> isinstance([7,8,9], Iterable) # check list object
True
>>> isinstance(1789, Iterable) # check an integer.
False

Finally, what if you want to implement subscript loops like Java for lists? Python’s built-in enumerate function turns a list into an index-element pair, so that the index and the element itself can be iterated simultaneously in the for loop.

>>> for i, value in enumerate(['Python', 'C++', 'Java']):
...     print(i, value)
...
0 Python
1 C++
2 Java

In the for loop above, two variables are referenced at the same time, which is very common in Python, such as the following code.

>>> for x, y in [(1, 'Python'), (2, 'C++'), (3, 'Java')]:
...     print(x, y)
...
1 Python
2 C++
3 Java

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.