We can access each element of the list or traverse a list using a for loop or a while loop.
i = 0
colors = ['red','green','yellow']
while i < len(colors):
print(colors[i])
i = i+1
Output
red green yellow
You can use for loop to iterate over a list. Here are some examples:
Program (forloop1.py)
colors = ['orange', 'green', 'blue']
for color in colors:
print(color)
Output
orange green blue
Program (forloop2.py)
for fruit in ['apple', 'banana', 'mango']:
print(fruit)
Output
apple banana mango
A nested list is a list that appears as an element in another list. In this list, the third element is a nested list:
>>> a = ["hello", 2.0, 5, [10, 20]]
If we print a[3], we get [10, 20].
To extract an element from the nested list, we can proceed in two steps:
>>> elt = a[3]
>>> elt[0]
10
Or we can combine them:
>>> a[3][1]
20
Bracket operators evaluate from left to right, so this expression gets the third element of list and extracts the first element from it.
Nested lists are often used to represent matrices. For example, the matrix:
1 2 3
7 8 9
4 5 6
might be represented as:
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix is a list with three elements, where each element is a row of the matrix.
We can select an entire row from the matrix in the usual way:
>>> matrix[1]
[4, 5, 6]
Or we can extract a single element from the matrix using the double-index form:
>>> matrix[1][1]
5
The first index selects the row, and the second index selects the column.
If you want to break a string into words, you can use the split method:
>>> s = 'Just drink more coffee.'
>>> t = s.split()
>>> print(t)
['Just', 'drink', 'more', 'coffee.']
>>> print(t[2])
more
You can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses / (slash) as a delimiter:
>>> s = '12/03/2021'
>>> s.split('/')
['12', '03', '2021']
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
In this case the delimiter is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, "", as a delimiter.