Python has a built-in list type. The list literal is created using square bracket syntax '[]'. All the items (elements) inside these square brackets is what comprises the list.
Below is an example of of an alphabetical list holding three elements. Each element can be selected using the slice syntax [], and the length of the list can be shown using the len() function:
sports = ['running','cycling','swimming']
print (sports)
print (sports[0])
print (sports[2])
print (len(sports))
['running', 'cycling', 'swimming'] running swimming 3
When assigning a list to a new variable with the '=' operand, it is important to note that the list is not 'copied', but rather the same list is assigned to both its original variable and the new one:
s = sports ## List is not copied
s
['running', 'cycling', 'swimming']
Values can be used from a list for many different purposes. A simple one is to take an individual value from a list, for example the first element, and incorporate it into an f-string:
message = f"The first sport in the list is {sports[0].title()}."
message
'The first sport in the list is Running.'
Perhaps a value is not correct, or needs to be changed. It is possible to change any value in a list, for example swimming is changed to football below:
sports[2] = 'football'
sports
['running', 'cycling', 'football']
Lists can be sorted in many different ways. An obvious and useful choice is alphabetical sorting, Python has a sort() method that does just that:
print(sports)
sports.sort()
sports
['running', 'cycling', 'football']
['cycling', 'football', 'running']
The sort() method changes the order of a list permanently. If a list needs to be temporarily sorted, the sorted() function is the better option.
In Python a 'FOR' loop is used to iterate over a sequence. This sequence can be a list, tuple, dictionary, set or string. The FOR loop is an extremely useful way of looking at each element in a list. The next example iterates through the list called 'counting' and prints each element within:
counting = [1, 2, 3, 4, 5]
for num in counting:
print (num)
1 2 3 4 5
Next, instead of printing each element, the FOR loop iterates though the counting list. Each time an element is reached, the value is added to the 'sum' variable. After the FOR loop has completed, the sum of all the numbers in the counting list is printed:
sum = 0
for num in counting:
sum += num
sum
15
By using the IN construct it is also possible to check if an element is in fact present. The next example checks if a specific string is present in the sports list, depending on how the if statement evaluates, a confirmation message is printed:
if 'running' in sports:
print ('running is in the list')
else:
print ('running is not in the list')
if 'golf' in sports:
print ('golf is in the list')
else:
print ('golf is not in the list')
running is in the list golf is not in the list
A simplier way to achieve the same evaluation as above is to use 'in' with the print function. If the string is present in the list, the output is true:
print('running' in sports)
print('golf' in sports)
True False
In Python the range() function returns a sequence of defined numbers. This range starts at 0 (n-1). By using range() in a FOR loop, it is possible to build a numeric FOR loop:
for i in range(5):
print(i)
0 1 2 3 4
Python has a while loop built-in. This is very useful when needing to excute a set of statements while a condiction is true. The example below prints the value of the variable 'i' while the value is less than 5:
i = 1
while i < 5:
print(i)
i += 1
1 2 3 4
It is possible to break out of the while loop when a certain condition is met. For example, once the value of 'i' is equal to 3:
i = 1
while i < 5:
print(i)
if i == 3:
break
i += 1
1 2 3
Conversely, it is also possible to continue when a condition is met. Here, the current iteration is stopped, and the program continues with the next:
i = 1
while i < 5:
i += 1
if i == 3:
continue
print(i)
2 4 5
Appending to a list in Python is straightforward. It is important to note that when appending to a list, the original list is modified.
print(sports)
sports.append('tennis')
print(sports)
['cycling', 'football', 'running'] ['cycling', 'football', 'running', 'tennis']
To append an element at a specific location in the list, the insert command works, which requires the position followed by the element to insert:
sports.insert(0,'golf')
sports
['golf', 'cycling', 'football', 'running', 'tennis']
A pattern used often to build up a list is to start with an empty list and append elements to it:
building = []
building.append('one')
building.append('two')
building.append('three')
print(building)
['one', 'two', 'three']
Some basic statistics can be run on lists. Below a range of numbers is created, and the min() and max() values are reported:
numbers = list(range(15))
numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
max(numbers)
14
min(numbers)
0
This post explains what lists are and how to use them. Adding to a list, changing the order of a list, as well as various methods to manipulate lists was shown. A brief introduction to the concept of iteration using 'IN' and 'FOR' was also discussed.