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.
name_list = ["mary", "john", "paul"]
len(name_list)
>> 3
You can add an item into a list using the
append
functionname_list.append("eric")
name_list
>> ['mary', 'john', 'paul','eric']
len(name_list)
>> 4
Items in a list can be retrieved as follows:
name_list[0]
>> 'mary'
name_list[3]
>> 'eric'
name_list[0:2] #this retreives the first three elements (0, 1, 2) from the list
>> ['mary', 'john', 'paul']
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):
name_list = ["mary", "john", "paul","eric"]
name_list.sort()
name_list
>> ['eric','john','mary','paul']
num_list = [334,23,1,54]
max(num_list)
>> 334
min(num_list)
>> 1
len(num_list)
>> 4
Last modified 4yr ago