Python loop through a list

In this Python tutorial, we will discuss the Python loop through a list. Here we will also cover the below examples:

  • Python loop through a list of strings
  • Python loop through list with index
  • Python loop through list of dictionaries
  • Python loop through list and write to file
  • Python loop through list with range
  • Python loop through list and create dictionary
  • Python loop through list backwards
  • Python loop through list of lists
  • Python loop through list and remove items
  • Python loop through list and change values
  • Python loop through list and append to string
  • Python loop through list add to dictionary
  • Python loop through list and get index

Python loop through a list

  • To iterate through a list in python we can easily use the range() method. This method returns a sequence of items and it can be used to combine a for loop with range() function to iterate over a list.
  • There are various method to perform this task.
    • By using for loop method
    • By using list comprehension method
    • By using enumerate method

Syntax:

Here is the Syntax of range() function

range(start,stop,[step])
  • It consists of few parameters
    • Start: This is an optional parameter and by default its value is 0.
    • Stop: This parameter specifies at which position we have to stop the integer value.
    • Step: This parameter specifies the incrementation and by default value is 1.

Note: This function creates the sequence of integers from the first value to the last value, but the end value does not include the range() function parameter.

Source Code:

my_lis = [9, 1, 16, 86, 92]
  
iter_len = len(my_lis)
for e in range(iter_len):
    print("Iterate through list:",my_lis[e])

In the above code first, we have created a list and assign them integers numbers. Now we have to find the length of the list by using the len() function and it will display the number of length that is 5. After that, we have to use for loop along with the range function.

Here is the execution of the following given code

Python loop through a list
Python loop through a list

By using for loop method

To iterate through a list in python, we can use for loop method.

Syntax:

for var_name in listname:

Example:

my_lis = [16, 29, 45, 83]

for m in my_lis:
    print(m)

Here is the Screenshot of the following given code

Python loop through a list using for loop method
Python loop through a list using for loop method

By using list comprehension method

In Python, if we want to create a single line of code to iterate a list then we can use the list comprehension method.

Syntax:

[statement for item in list]

Source Code:

num_lis = [36,84,12,45,94,51] 
[print(l) for l in num_lis] 

In this example, print(l) is the statement, and ‘l’ is the variable name that means a value of iterable.

Output:

Python loop through a list by using list comprehension
Python loop through a list by using list comprehension

By using enumerator method

In Python to iterate a list, we can also use the enumerator() method. it is a built-in function in Python. This method helps the user to convert enumerator objects to lists and tuples.

To check how many iterations have been occurred in the loop we can use the enumerator() function in Python.

Syntax:

enumerate
         (
          iterable,
          start
         )
  • It consists of two parameters
    • iterable: It is an object.
    • Start: It is an optional parameter and by default its value is 0.

Source Code:

enu_lis = [17,18,19,20]

for f, nw_val in enumerate(enu_lis):
    print (f, "-",nw_val)

Here is the Screenshot of the following given code

Python loop through a list by using enumerator method
Python loop through a list by using the enumerator method

Read: For loop vs while loop in Python

Python loop through a list of strings

  • Let us see how to iterate a list of strings through for loop.
  • By using zip() function we will create an iterator and this method produces a zip object which is an iterator of tuples.

Example:

new_lis = [9,2,4,5,6] 
Country_name = ['Afghanistan','Cyprus','Cuba','Germany','Africa'] 
for (m, n) in zip(new_lis, Country_name): 
    print ("Iterate a list:",m,n) 

In the above code, the iterator objects are new_lis and country_name. Now we can use the zip function to combine these iterator objects and returns some strings and integers which are present in the list.

Here is the implementation of the following given code

Python loop through a list of strings
Python loop through a list of strings

Read: Python while loop continue

Python loop through list with index

  • Here we can see how to iterate a list with index through loop in Python.
  • To perform this task we can easily use the map() and lambda function. In python to create an inline function we can apply lambda statements and to convert items in an iterable without using for loop, we can use the map() function.

Example:

new_lis =['John','Peter','Smith','Chris']
 
new_out = map(lambda n: (n, new_lis[n]), range(len(new_lis)))
print("Iterate list via index",list(new_out))

In the above code first, we will initialize a list. Now create a map function and assign a lambda statement as an argument to iterate a list with an index.

Here is the output of the following given code

Python loop through list with index
Python loop through the list with index

Alternative example to check how to iterate a list with index by using the enumerator method.

Source Code:

nu_list = [23,28,29,40]

for z, new_values in enumerate(nu_list):
    print (z, "|",new_values)

Implementation:

Python loop through list with index method
Python loop through the list with index method

Read: Python for loop index

Python loop through list of dictionaries

  • Let us see how to iterate a list of dictionaries through the loop in Python.
  • To solve this problem we can apply the range() function. This method returns a sequence of items and it can be used to combine a for loop with range() function to iterate over a list.

Syntax:

range(
     start,
     stop,
     [step]
    )

Example:

Let’s take an example and check how to iterate a list of dictionaries through the loop.

my_ne_lis = [{'o': 42}, {'z': 52}, {'y': 19}]
for new_index in range(len(my_ne_lis)):
    for new_key in my_ne_lis[new_index]:
        print(my_ne_lis[new_index][new_key])

Here is the Screenshot of the following

Python loop through list of dictionaries method
Python loop through a list of dictionaries method

Read: Python while loop multiple conditions

Python loop through list with range

In Python to perform this task, we can use the slicing method to do this first we create a range in the list from the first value to the last value, but the end value does not include in this example.

Syntax:

slice(start,stop,step)

Note: This method always returns an object which contains elements in the given range.

Source Code:

my_list = ["j","i","q","w","o"]

for m in my_list[2:4]:
    print("Iterate list with range:",m)

In this example first, we will initialize a list and assign them to string characters. Now use a slicing method and assign the start value ‘2’ as an argument and it will display the result ‘q’ along with that we have to assign a value for the stop that is ‘4’.

Output:

Python loop through list with range
Python loop through the list with a range

Read: How to create a list in Python

Python loop through list and create dictionary

  • In Python to create a dictionary by using a for loop through the list. we have to create an ordered list and compare the values from the list to ordered numbers.
  • In this example, we have the corresponding item in the list as the value. Now we have to set an item in a dictionary by using dictionary[count] = item in this case count variable is the key.

Code:

to_lis = [82, 73, 156,234,346]
my_coun = 0
new_dictionary = {} 

for n in to_lis:
    new_dictionary[my_coun] = n
    my_coun+=1
print(new_dictionary)

Here is the Screenshot of the following given code

Python loop through list and create dictionary
Python loop through the list and create a dictionary

Read: Python dictionary append

Python loop through list backwards

  • In Python to iterate over a list in Reverse order, we can apply the loop and reversed() method. This method takes only a single argument that is sequence and it returns an iterator item in reverse order.

Syntax:

reversed(sequence)

Let’s take an example and iterate the list in a reverse order using for loop

Source Code:

new_list = [92,46,73,28,14,13]
for n in reversed(new_list):
    print("Backward iterated list:",n)

Here is the execution of the following given code

Python loop through list backwards
Python loop through list backward

Read: Check if a list is empty in Python

Python loop through list of lists

  • Let us see how to iterate a nested list in Python by using for loop method.
  • To iterate every element of a list we can apply for-loop method.

Example:

new_lis = [[82,36,10], [15, 19, 32], [18, 46, 57]]
for list in new_lis:
    for new_num in list:
        print (new_num)

Here is the execution of the following given code

Python loop through list of lists
Python loop through a list of lists

Python loop through list and remove items

  • In Python to remove items from a list, we can use for loop method.
  • Let us assume we have a list of numbers and we want to remove items from a list. To do this task first we will create a list and iterate each element.
  • In this example, if you want to remove an item from the list then you can use the remove() function.

Source Code:

numbers_list = [11,17,82,34,22,76,91]

for value in list(numbers_list):
    if value == 22 or value == 34:
        numbers_list.remove(value)
print(numbers_list)

Here is the Screenshot of the following given code

Python loop through list and remove list
Python loop through the list and remove list

Read: How to draw a shape in python using Turtle

Python loop through list and change values

In python, we can change values in a Python list by using a for loop method. To do this task we can use the python range() function. This method returns a sequence of items.

Example:

new_list = [19,29,31,42,51,48]
for m in range(len(new_list)):
    new_list[m] = new_list[m] * 3
print(new_list)

In the above code, we have to change all the values which are available in the list. To check how it works we have to multiply all the integers by 3.

Here is the output of the following given code

Python loop through list and change values
Python loop through list and change values

Read: Python list methods

Python loop through list and append to string

  • Let us see how to append to a string in a for loop by using item() method.
  • In this example we have to initialize a list and put the elements in the list. Now use for loop method and concatenate all the string characters by using += item operator. This method is a built-in function in Python.

Source Code:

new_lis = ['Adam', 'Gilchrist', 'Hayden']
d = ""
for item in new_lis:
   d += item
print("append strings:",d)

Here is the execution of the following given code

Python loop through list and append to string
Python loop through the list and append to a string

Read: Python Dictionary Methods

Python loop through list add to dictionary

  • Here we can see how to iterate a list and add it to a dictionary.
  • To perform this particular task we can apply the splitlines() method. This is an in-built function in Python and it is used to break the string depending on the lines.

Example:

Let’s take an example and check how to iterate a list in python and add it to a dictionary.

final_result = '''Name
 George
age
 40'''

new_lis = final_result.splitlines()
my_dict = {}
new_dicti_key=''
for n in new_lis:
    if not n[0]==(" "):
        new_dicti_key=n
        my_dict[n] = []
    else:
        my_dict[new_dicti_key].append(n)

print(my_dict)

Here is the Screenshot of the following given code

Python loop through list add to dictionary
Python loop through list add to dictionary

Python loop through list and get index

  • Let us see how to iterate a list and get the index value in Python.
  • To do this task we can use enumerator() method. This method takes in an iterable item as a parameter such as list and returns in the form of enumerator object.

Source code:

list_numbers = ['Lebanon','Mauritius','Mexico','Newzealand']

for n, new_values in enumerate(list_numbers):
    print (n, "|",new_values)

Here is the execution of the following given code

Python loop through list and get index
Python loop through the list and get index

You may like the following Python tutorials:

In this Python tutorial, we will discuss the Python loop through a list. Here we will also cover the below examples:

  • Python loop through a list of strings
  • Python loop through list with index
  • Python loop through list of dictionaries
  • Python loop through list and write to file
  • Python loop through list with range
  • Python loop through list and create dictionary
  • Python loop through list backwards
  • Python loop through list of lists
  • Python loop through list and remove items
  • Python loop through list and change values
  • Python loop through list and append to string
  • Python loop through list add to dictionary
  • Python loop through list and get index