Lists with Loops
Learn to use lists with the help of loops in Python.
We'll cover the following...
We'll cover the following...
The for loop with lists
The individual values in a list are accessed through an index number. The for loop variable can be used as an index number. However, the list values can also be used directly in a for loop.
The following program demonstrates the various ways of accessing list elements:
Python 3.10.4
vals = [-5, 'Python', 3.8]print("Using loop variable as a list index")for i in [0,1,2]:print(vals[i])print("\nDirectly accessing the elements")for v in vals:print (v)mix = ['a',1,2.5,'i',50,6,'m',4.4,6.7,'s','@educative']print('\nList index using "len()" in range()')for v in range(len(mix)):print (mix[v])
In the code above:
- The new item is the
len ( )function, which is used to get the length of the list. - The first
forloop accesses the list values with the help of the loop variablei. - The second
forloop directly accesses the list values. - The third
forloop accesses the list values with the help of loop variablevand the functionsrangeandlen.
The while loop with lists
We usually use the while loop to deal with lists when the number of iterations is not fixed. For a simple example, let’s say we want to generate n terms of a Fibonacci sequence and store it in a list, where n is the user input.
A Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones except the first two terms.
Let’s start by noting a few terms of this sequence: ...