Lists
Python has a number of built-in composite data structures: tuples, lists, sets, dictionaries. Here we take a look at lists and dictionaries.
A list stores many values in a single structure.
= [267, 1332, 1772, 1994, 493, 1373, 1044, 156, 1515, 1788] # array of years
events print('events:', events)
print('length:', len(events))
print('first item of events is', events[0]) # indexing starts witgh 0
2] = 1773 # individual elements are mutable
events[print('events is now:', events)
1239) # append at the end
events.append(606) # append at the end
events.append(print('events is now:', events)
4) # remove element #4
events.pop(print('events is now:', events)
267) # remove by value (first occurrence) events.remove(
= [] # start with an empty list
a 'Vancouver')
a.append('Toronto')
a.append('Kelowna')
a.append(print(a)
3] # will give an error message (past the end of the array)
a[-1] # display the last element; what's the other way?
a[# will display all elements
a[:] 1:] # all elements starting from #1
a[1] # ending with but not including #1 a[:
Lists can be heterogeneous and nested:
= [11, 21., 3.5]
a = ['Mercury', 'Venus', 'Earth']
b = 'hello'
c = [a, b, c]
nestedList print(nestedList)
Exercise 5.1: double subsetting
How would you extract element “Earth” from nestedList
?
You can search inside a list:
'Venus' in b # returns True
'Pluto' in b # returns False
'Venus') # returns 1 (positional index)
b.index(1].index('Venus') # same nestedList[
And you sort lists alphabetically:
b.sort()# returns ['Earth', 'Mercury', 'Venus'] b
Exercise 5.2
Write a script to find the second largest number in the list [77,9,23,67,73,21].