Search code snippets, questions, articles...

Loop through a list in Python

If you working on lists in Python and want to retrieve items of the list using loop then this post is for you.
companies = ['Devsheet', 'Tesla', 'Apple', 'Microsoft']

for company in companies:
    print(company)

# -> Devsheet
# -> Tesla
# -> Apple
# -> Microsoft
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

We are describing multiple ways to loop through a list in Python and use the items of lists in each iteration. We mostly use a For loop for iterating over list items.

Loop through a list using For loop

You can use For loop in Python to access the list items in a loop. In the main code snippet also, we are using a simple for loop that will print the list item in each iteration.

Basic Syntax

for item in List

Example

numbers = [10, 20, 30]

for item in numbers:
  print('Item is : ', item)

# -> Item is :  10
# -> Item is :  20
# -> Item is :  30

Loop through a list of dictionaries

students = [
  {'id': 1, 'name': 'Stuart'},
  {'id': 2, 'name': 'Rick'},
  {'id': 3, 'name': 'Carol'}
]

for student in students:
  print("Id is : ", student['id'], end=' ')
  print("Name is : ", student['name'])

# -> Id is :  1 Name is :  Stuart
# -> Id is :  2 Name is :  Rick
# -> Id is :  3 Name is :  Carol

Loop through a list using List Comprehension

You can also use List Comprehension to loop through a list. Here we can write our code in one line to iterate over a list.

Code Example

my_list = ["a", "b", "c", "d"]

[print(x) for x in my_list]

Output

a
b
c
d

Iterate over a List using while loop

The while loop in Python can also be used to loop through a list. You can understand it using below code snippet.

While loop on python list example

car_list = ['Hyundai', 'TATA', 'Mahindra']
 
counter = 0

while counter < len(car_list): 
  print(car_list[counter])
  counter += 1

Output

Hyundai
TATA
Mahindra
fruits = ['Banana', 'Apple', 'Orange']
 
for index, fruit in enumerate(fruits): 
    print('Index is :', index, end='. ')
    print('Item is : ', fruit)

# Output
# -> Index is : 0. Item is :  Banana
# -> Index is : 1. Item is :  Apple
# -> Index is : 2. Item is :  Orange
You can use enumerate() function of python to loop through a list. This will give you the item as well as the index of the item in each iteration.
numbers = [1, 2, 3, 4, 5]

result = list(map(lambda x : x * x, numbers))

print(result)
# -> [1, 4, 9, 16, 25]
You can apply a function on each item of the list using the map() function. You can use the lambda function along with this to make it short.
Was this helpful?
0 Comments