Python loop through list
In this post, you will learn how to loop through a list using the Python programming language.
A list is a sequence of indexed and ordered values, like a dynamic size array. It is mutable, which means we can change the order of elements in a list. It contains a list of any type of data object with a comma separated and enclosed within a square bracket. The elements in a list are indexed, starting with 0 , 1, and so on. In the development process, we may come to the situation where we need to loop through the list. Generally, developers use simple for and while loops when iterating through various kinds of iterators, but Python provides a lot of helper functions that can make your code simpler and even faster. Here, we have mentioned most of them with simple examples.
Python loop through list using for loop without index
For loop is available in almost every programming language. The Python for loop is used to loop through an iterable object, like a list, tuple, set, etc. In the given Python program, we have used a for loop to iterate over a list without displaying the index value.
# Python code to iterate over a list
# using for loop
list_elems = ['bread', 'cookies', 'chocolate', 'tea', 'cake']
# Iterate over the list
for value in list_elems :
print(value, end=' ')
Output of the above code-
bread cookies chocolate tea cake
Python loop through list using for loop with index
In the given Python program, we have used a for loop to iterate over a list and displaying their index value.
list_elems = ['bread', 'cookies', 'chocolate', 'tea', 'cake']
# Iterate over the list
for value in range(0,len(list_elems)):
print(value, end=' ')
Output of the above code-
0 1 2 3 4
Python loop through list using for loop with enumerate type
Python enumerate() function can be utilised to repeat the list in an enhanced way. This method adds a counter to the iterator and returns it (the enumerate object). It makes it simpler to monitor the substance of an iterable article. Subsequently, it reduces the overhead of keeping a check of the components during the iteration operation. Here, we have used a for loop with enumerate type to iterate over a list.
list_elems = ['chair', 'fan', 'bulb', 'table', 'cooler']
# Iterate over the list
for value,char in enumerate(list_elems):
print(char, end=' ')
Output of the above code-
chair fan bulb table cooler
Python loop through list using for loop with sliced lists
In the given Python program, we have iterated over the list elements with sliced lists.
list_elems = ['bread', 'cookies', 'chocolate', 'tea', 'cake']
# Iterate over the list
for value in range(1,len(list_elems)):
print(list_elems[value-1:value], end='')
print(list_elems[-1:])
Output of the above code-
['bread']['cookies']['chocolate']['tea']['cake']
Python loop through list using while loop
The while loop is used to repeat a section of code an unknown number of times until a specific condition is met. Here, we have used a while loop to iterate over the given list.
list_elems = ['bread', 'cookies', 'chocolate', 'tea', 'cake']
# Getting length of list
length = len(list_elems )
i = 0
# Iterating using while loop
while i < length:
print(list_elems [i])
i += 1
Output of the above code-
bread
cookies
chocolate
tea
cake
Python loop through list using for loop and range
The range() method of Python is helpful while dealing with loops, conditional statements. It returns a sequence of numbers, starting from 0 by default and incrementing by 1 (by default), and stops before a specified number. We can use Python's range() method in combination with a for loop to iterate over a list.
# Python code to iterate over a list
list_elems = ['bread', 'cookies', 'chocolate', 'tea', 'cake']
# getting length of list
length = len(list_elems )
# Iterating the index
# same as 'for i in range(len(list_elems))'
for i in range(length):
print(list_elems[i])
Output of the above code -
bread
cookies
chocolate
tea
cake
Python loop through list using a lambda function
Lambda is an anonymous function that contains any number of arguments but only one expression. This function is defined without a name. Here, we have used the lambda function to loop over the list.
list_elems = [42, 74, 22, 65, 23, 52]
y = list(map(lambda x:x, list_elems))
print(y)
Output of the above code -
[42, 74, 22, 65, 23, 52]
Python loop through list using Python numpy
NumPy is an open-source numerical Python library. It provides an efficient multi-dimensional iterator object called np.nditer to iterate over arrays. Here is an example-
import numpy as np
list_elems = ['bread', 'cookies', 'chocolate', 'tea', 'cake']
for x in np.nditer(list_elems):
print(x)
Output of the above code -
(array('bread', dtype='<U5'), array('cookies', dtype='<U7'), array('chocolate', dtype='<U9'), array('tea', dtype='<U3'), array('cake', dtype='<U4'))
Related Articles
Multiply all elements in list PythonFind element in list Python
Multiply each element of a list by a number in Python
Convert List to Dataframe Python
Convert tuple to list Python
Python convert list to numpy array
How to shuffle a list in Python
Print hollow diamond pattern in Python
Python *args **kwargs
Write a python program to sum all the numbers in a list
Shuffle list python
Convert array to list Python
Remove element from list Python
Convert list to dictionary Python
Python dict inside list
Convert list to string Python
Remove last element from list Python
Convert string to list Python
Python add list to list
Difference between tuple and list in Python
Alphabetical order Python
Python | Generate QR Code using pyqrcode module