A python list is a collection of elements of same or different types.
Iterating over a list is the most required operation for many tasks such as addition of its elements, finding the largest element in the list etc.
This article will explain different ways in which a list can be iterated in python.
Method 1: Using for loop with index
A list is an indexed collection meaning all its elements have numeric indexes starting with 0.
A list can be iterated using for loop starting with 0 till the length of the list using range function.
for loop with
range function iterates from 0 till the number provided to the range function as argument.
# create a list strings = ["Python","fun", "is", "learning"] # calculate length of list total_items = len(strings) # iterate using for loop for count in range(total_items): print(strings[count])
Above example prints
for loop along with
inoperator is a simplest way to iterate a list. Syntax is
for <variable> in <list>:
variable holds the next list item in every iteration starting with first.
# create a list strings = ["Python","fun", "is", "learning"] # iterate using for in loop for word in strings: print(word)
Output of above example is
This method works in the same way as the indexed
forloop in that the elements are accessed using index but it uses a while instead of for.
# create a list strings = ["Python","fun", "is", "learning"] # calculate length of list total_items = len(strings) # initialize loop counter count = 0 # iterate using while loop while count < total_items: print(strings[count]) # increment counter count += 1
Output is the same as above methods.
Method 4: Using enumerate()
Python’s built-in function
enumerate accepts an iterable(such as list) as argument and returns a list of tuples where each list element is a tuple whose first element is a count and second is the list item itself.
where first argument is the iterable and second is a counter.
Counter is optional and defaults to 0 if the second argument is not provided.
#list of string strings = ["Python","fun", "is", "learning"] # assign the return value from enumerate to variable enumerateType = enumerate(strings) # convert to list enumerate_list = list(enumerateType) # print its value print(enumerate_list) # iterate the list for i, word in enumerate_list: print(i,word)
Output of above code is
Look, the return value of
enumerate when converted to a list is a list of tuples and how it is iterated.
It is also possible to modify the first value of tuples to start with some other value by providing it as the second argument to
enumerateType = enumerate(strings, start = 10)
With start value set to 10, the list of tuples will change to
Do not forget to click the clap if the article was helpful.1