In this lesson I will do some examples of using the for loop with the list element in Python.
For list Python – Print a list in reverse order using the for loop
This problem can have several solutions, we will analyze some of them.
The first solution makes use of the reversed() function, to invert a list, the second one uses the length of the list, the len() function.
Let’s start by analyzing the first solution in detail.
First we create a list of elements: numbers = [1, 2, 3, 4, 5], then we use the existing function reversed() to reverse the elements of a list. So we print the inverted elements using the for loop in Python on the list.
Here is a possible solution:
numbers = [1, 2, 3, 4, 5] numbers_reversed = reversed(numbers) for number in numbers_reversed: print(number)
Let’s now work out a second solution, calculating the length of the list from which we will subtract one. In this way we find the index of the last element of the list. Then we will use the appropriate for loop.
Here is the complete code of the second solution to our algorithm that uses the for on lists in Python:
numbers = [1, 2, 3, 4, 5] n_numbers = len(numbers) - 1 for i in range (n_numbers, -1, -1): print(numbers[i])
For list Python – Compute the cube of all elements of a list
Let’s create a list of integers. With the for loop we calculate the cube of each element and print the list. We use the len function to determine the length of the list. Finally we cycle through the modified list to print the elements.
numbers = [1, 2, 3, 4, 5] for i in range(len(numbers)): numbers[i] = numbers[i] * numbers[i] * numbers[i] for number in numbers: print(number)
A second solution involves simply using the function in Python to calculate the powers of a number, the pow() function.
In our case we will need to raise to the cube. Then we cycle through the list with the for loop in Python.
Here is the complete sample code:
numbers = [1, 2, 3, 4, 5] for i in range(len(numbers)): numbers[i] = pow(numbers[i],3) for number in numbers: print(number)
These are just some simple examples of using the for loop with lists in Python, in the next lessons we will develop many other examples.