Search⌘ K

Lists with Loops

Explore how to work with lists using for and while loops in Python. Understand how to access list elements by index or value, create Fibonacci sequences, and practice problems like palindrome tests and sorting. This lesson builds foundational skills for handling sequences and loops in programming.

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 for loop accesses the list values with the help of the loop variable i.
  • The second for loop directly accesses the list values.
  • The third for loop accesses the list values with the help of loop variable v and the functions range and len.

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: 0,1,1,2,3,5,8,13,21,34,0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … ...