Lists with Loops
Learn to use lists with the help of loops in Python.
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:
Press + to interact
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
for
loop accesses the list values with the help of the loop variablei
. - The second
for
loop directly accesses the list values. - The third
for
loop accesses the list values with the help of loop variablev
and the functionsrange
andlen
.
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 ...