This tutorial includes 3 examples showing how to write for loop in Python.
Example 1 of for loop in Python
The following creates a list called cars, and we can then use for loop to print out each item in the list.
# create a list of cars
cars = ["Tesla", "Ford", "Toyota"]
# print out the list
print(cars)
# print out the items in the list one by one via for loop
for brand in cars:
print(brand)
The following is the output, which includes a complete list format and for loop one-by-one format.
['Tesla', 'Ford', 'Toyota'] Tesla Ford Toyota
Example 2 of for loop in Python
enumerate()
will return both index and element. You can use it to access indexes of elements when looping. The following is an example showing how to add an index to elements.
# define a list, check data type, and print it out
cars = ["Tesla", "Ford", "Toyota"]
print('Type of cars:', type(cars))
print('Content of cars:', cars)
# use enumerate() to transform the data list, check data type
cars_temp=enumerate(cars)
print('Type of cars_temp:',type(cars_temp))
print('Content of cars_temp:',cars_temp)
# use for loop to print it out
for brand in cars_temp:
print(brand)
The following is the output.
Type of cars: <class 'list'> Content of cars: ['Tesla', 'Ford', 'Toyota'] Type of cars_temp: <class 'enumerate'> Content of cars_temp: <enumerate object at 0x000001C81FCC9958> (0, 'Tesla') (1, 'Ford') (2, 'Toyota')
Example 3 of for loop in Python
The following is another example using enumerate()
in for loop in Python.
# define a list of cars
cars = ['Tesla', 'Ford', 'Toyota']
# use for loop to print each item in the list out, with index
for idx, x in enumerate(cars):
print(idx, x)
The following is the output, which includes the index as well as each item in the list.
0 Tesla 1 Ford 2 Toyota