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:
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, ...