Introduction
Python is a powerful and popular language that is widely used for its simplicity and efficiency in programming. One of the most commonly used data structures in Python is the list. A list is an ordered collection of elements that can store different types of data. Iterating a list in Python simply means traversing through each element of the list in sequence. In this tutorial, we will take an in-depth look at iterating a list in Python and explore various techniques to effectively access and manipulate its elements. Whether you're a beginner or an experienced programmer, this tutorial will help you understand the basics of iterating lists in Python. So let's get started!
Table of Contents :
- Iterating a list in Python
- Iterating Python list using the for loop
- Iterating Python list using the enumerate() function
Iterating a list in Python :
We can iterate a list in Python using :
- simple for loop
- enumerate() function
Iterating Python list using the for loop :
- We can use a for loop to iterate over a list in Python.
- The basic syntax of list iteration is as follows :
for item in list_name:
# implement logic
- In every iteration, one element in assigned to the item variable.
- the iterations begin with the first element of the list and goes till the last.
- We can then use this item variable to implement our logic.
- Code Sample :
my_list = [1, 2, 3, 4]
# iterating the list
for item in my_list:
print("item = ", item)
# Output
# item = 1
# item = 2
# item = 3
# item = 4
Iterating Python list using the enumerate() function :
- Sometimes we need the value of the list item as well as its index inside our loop body.
- For this purpose python provides an
enumerate()
function. - enumerate() function return the list element and its index as a tuple.
- The syntax of list iteration using enumerate is as follows :
for index, item in enumerate(list_name):
# implement logic
- We can also specify the starting index in the enumerate function.
- The iterations will start from this start index.
- The syntax of list iteration using enumerate and start index is as follows :
for index, item in enumerate(list_name, start_index):
# implement logic
- Code Sample :
my_list = [1, 2, 3, 4]
# iterating using enumerate function
for index, item in enumerate(my_list):
print(f"Item {item} is at index {index}")
# Output
# Item 1 is at index 0
# Item 2 is at index 1
# Item 3 is at index 2
# Item 4 is at index 3
Prev. Tutorial : Lists
Next Tutorial : Index of an element