7. Lists
So far we have used variables to store a single value. Sometimes it is useful to store multiple values into a single variable using a list.
1
name_list = ["mary", "john", "paul"]
2
len(name_list)
3
>> 3
Copied!
You can add an item into a list using the append function
1
name_list.append("eric")
2
name_list
3
>> ['mary', 'john', 'paul','eric']
4
len(name_list)
5
>> 4
Copied!
Items in a list can be retrieved as follows:
1
name_list[0]
2
>> 'mary'
3
4
name_list[3]
5
>> 'eric'
6
7
name_list[0:2] #this retreives the first three elements (0, 1, 2) from the list
8
>> ['mary', 'john', 'paul']
Copied!
Python considers the first item in a list to be item 0 (zero), second item to be item 1, and so on.
You can also perform different functions on a list, such as sorting, and finding maximum, minimum and length (number of items):
1
name_list = ["mary", "john", "paul","eric"]
2
name_list.sort()
3
name_list
4
>> ['eric','john','mary','paul']
5
6
num_list = [334,23,1,54]
7
max(num_list)
8
>> 334
9
min(num_list)
10
>> 1
11
len(num_list)
12
>> 4
Copied!
Last modified 2yr ago
Copy link