Topic 5
Tuples and Lists
IN WEEK 4
§ functions
§ decomposition – create structure
§ abstraction – suppress details
§ from now on will be using functions a lot
6.0001 LECTURE 5 2
TODAY
§ have seen variable types: int, float, bool,string
§ introduce new compound data types
• tuples
• lists
§ idea of mutability
§ idea of aliasing
§ idea of cloning
6.0001 LECTURE 5 3
TUPLES AND LISTS
§ Tuple and list are two frequently used data structures in
Python.
§ They are part of a more general data structure known as
"collection".
§ Tuple and list are language built-in data structures.
§ A tuple is an ordered sequence of elements.
Ø tuples are defined using parentheses, eg, (1, "two", 3)
§ A list is also an ordered sequence of elements.
Ø tuples are defined using square brackets, eg, [1, "two", 3]
§ Both are non-scalar objects
6.0001 LECTURE 5 4
TUPLES AND LISTS
§ Elements in tuples and lists are accessible using indexes
§ Each has its own set of built-in methods
§ Some of the functions and notations apply to both, such as len
function and syntax for indexing
§ Elements in tuples and lists are heterogenous, these elements
do not have to have the same type
§ The main difference between the two:
Ø a tuple is immutable – once created, you cannot change it (similar
to string)
Ø while a list is mutable
6.0001 LECTURE 5 5
TUPLES
§ a tuple is an ordered sequence of elements, can mix element
types
§ cannot change element values, immutable (like a string)
§ represented with parentheses
t1 = () -> an empty tuple
t2 = (2,"mit",3) -> t2 is a tuple with 3 elements
len(t2) -> evaluate to 3, similar to strings
t3 = ("One",) -> t3 is a tuple with a single element, note the
comma at the end!
t4 = ("One") -> t4 is just a string "One", not a tuple!!!
t5 = t2 + t3 -> t5 is a new tuple (2,"mit",3, "One")
t2[1] = 4 -> gives error,
6.0001 LECTURE 5 because tuples cannot be
6
modified
INDEXING A TUPLE
§ As with strings, we can use index to get an individual element from
a tuple
t = (1, 2, "mit", 4, "True", 6.6, "7", 8, 9, "ten")
t[0] -> evaluate to 1
t[2] -> evaluate to "mit"
t[9] -> evaluate to "ten"
t[10] -> error: "IndexError: tuple index out of range"
§ Elements in a tuple can also be tuples (nested tuple)
tn = (1, 2, (3.1, 3.2), 4, (5, 6, 7))
tn[1] -> evaluate to 2
tn[2] -> evaluate to (3.1, 3.2)
6.0001 LECTURE 5 7
tn[2][1] -> evaluate to 3.2
SLICING A TUPLES
§ We can also create a new tuple out of an existing tuple using index
syntax. Note: no change to the existing tuple
§ The syntax is similar to the syntax used to get a new string out of
an existing string.
t = (1, 2, "mit", 4, "True", 6.6, "7", 8, 9, "ten")
t[1:2] -> evaluate to a new tuple(2,). Note the extra
comma at the end
t[1:5] -> evaluate to a new tuple(2,"mit",4,"True")
t[Link] -> evaluate to a new tuple (2,4)
t[1::2] -> evaluate to a new tuple (2,4,6.6,8,"ten")
t[-1::2] -> evaluate to a new tuple ("ten",)
t[-1::-2] -> evaluate 6.0001
to LECTURE
a new5 tuple ("ten",8,6.6,4,2)
EXAMPLE: SWAP TWO VARUES
§ conveniently used to swap variable values
x = y temp = x (x, y) = (y, x)
y = x x = y
y = temp
§ used to return more than one value from a function
def quotient_and_remainder(x, y):
q = x // y
r = x % y
return (q, r)
6.0001 LECTURE 5 9
(quot, rem) = quotient_and_remainder(4,5)
USING TUPLE IN LOOP
fruits = ("apple", "banana", "orange", "mango")
vegitables = ("carrot", "broccoli", "pea", "cabbage", "spinach")
grains = ("wheat", "rice", "barley")
def count_food (food):
fruit_c = vegitable_c=grain_c=0
for f in food:
if f in fruits:
fruit_c += 1
elif f in vegitables:
vegitable_c += 1
else:
grain_c += 1
return (fruit_c, vegitable_c, grain_c)
myfood = ("rice", "broccoli", "pea", "banana", "barley", "spinach")
print(count_food(myfood))
6.0001 LECTURE 5 10
LISTS
§ a list is an ordered sequence of information,
accessible by index
§ a list is denoted by square brackets, []
§ a list contains elements
• usually homogeneous (eg, all integers)
• can contain mixed types (not common)
§ list elements can be changed so a list is mutable
6.0001 LECTURE 5 11
INDICES AND SLICING
a_list = []
L = [2, 'a', 4, True]
L1 = [1] -> L1 is a list with one element,
note: no comma at the end
len(L) -> evaluate to 4
L[0] -> evaluate to 2
L[2]+1 -> evaluate to 5
L[3] -> evaluate to True
L[1:3] -> evaluate to a new list ['a', 4]
L[-[Link]-1] -> evaluate to a new list [True, 4]
L[4] -> gives an error
i=2 6.0001 LECTURE 5 12
L[i-1] -> evaluate to 'a' since the 2nd element is 'a'
LISTS CAN BE NESTED
L = [[1,2,3], [4,5], [6,7,8,9]]
len(L) -> evaluate to 3
L[-1] -> evaluate to [6,7,8,9]
L[-1][1] -> evaluate to 7
L2 = L + ['a','b'] -> merge two lists
L2 is [[1,2,3],[4,5],[6,7,8,9],[10],'a','b']
6.0001 LECTURE 5 13
CHANGING ELEMENTS
§ lists are mutable!
§ assigning to an element at an index changes the value
L = [2, 1, 3]
L[1] = 5
§ L is now [2, 5, 3], note this is the same object L
[2,5,3]
14
L
ITERATING OVER A LIST
§ compute the sum of elements of a list
§ common pattern, iterate over list elements
§ assuming L is a list of numbers:
total = 0 total = 0
for i in range(len(L)): for i in L:
total += L[i] total += i
print(total) print(total)
Notice:
• list elements are indexed from 0 to len(L)-1
• range(n)goes from 0 to n-1
15
OPERATION ON LISTS –
append method
§ add elements to end of list with [Link](element)
§ mutates the list!
L = [2,1,3]
[Link](5) -> L is now [2,1,3,5]
§ what is the dot?
• lists are Python objects, everything in Python is an object
• objects have data
• objects have methods
• access this informaEon by object_name.do_something()
• will learn more about these later 16
OPERATION ON LISTS –
extend method
§ to combine lists together use concatenation operator +,
to give you a new list
§ mutate list with [Link](some_list)
L1 = [2,1,3]
L2 = [4,5,6]
L3 = L1 + L2 -> L3 is [2,1,3,4,5,6]
L1, L2 unchanged
[Link]([0,6]) -> mutated L1 to [2,1,3,0,6]
6.0001 LECTURE 5 17
OPERATION ON LISTS -
REMOVING AN ELEMENT
§ delete element at a specific index with del(L[index])
§ remove element at end of list with [Link](), returns the removed
element
§ remove a specific element with [Link](element)
• looks for the element and removes it
• if element occurs mulDple Dmes, removes first occurrence
• if element not in list, gives an error
L = [2,1,3,6,3,7,0] # do below in order
[Link](2) -> mutates L = [1,3,6,3,7,0]
[Link](3) -> mutates L = [1,6,3,7,0]
del(L[1]) -> mutates L = [1,3,7,0] 18
6.0001 LECTURE 5
[Link]() -> returns 0 and mutates L = [1,3,7]
CONVERT LISTS TO STRINGS
AND BACK
§ convert string s to list with L=list(s), returns a list with
every character from s an element in L
§ can use [Link](c), to return a list containing two
substrings split on a character parameter c, splits on spaces if
called without a parameter
§ use ''.join(L) to turn a list of characters into a string, can
give a character in quotes to add char between every element
s = "I<3 cs" ̶˃ s is a string
list(s) ̶ returns ['I','<','3',' ','c','s']
˃
[Link]('<') ̶˃ returns ['I', '3 cs']
L = ['a','b','c'] ̶˃ L is a list
''.join(L) ̶˃ returns "abc"
6.0001 LECTURE 5 19
'_'.join(L) ̶˃ returns "a_b_c"
OTHER LIST OPERATIONS
§ sorted function
§ sort method
§ reverse method
§ and many more!
[Link]
L=[9,6,0,3]
sorted(L) ̶˃ returns sorted list, does not mutate L
[Link]() ̶˃ mutates L=[0,3,6,9]
[Link]() ̶˃ mutates L=[9,6,3,0]
6.0001 LECTURE 5 20
MUTATION, ALIASING, CLONING
Remember, Python Tutor is
your best friend to help sort
this out!
h"p://[Link]/
6.0001 LECTURE 5 21
LISTS IN MEMORY
§ lists are mutable
§ behave differently than immutable types
§ is an object in memory
§ variable name points to object
§ any variable poinAng to that object is affected
§ key phrase to keep in mind when working with lists is
side effects
6.0001 LECTURE 5 22
ALIASES
§ If variable contains a scalar object, the value is stored in the
variable.
a = 1 # here a contains scalar object 1
b = a # copy the value 1 stored in a to variable b
§ AHer the assignment, b iniIally contains the same value as a,
but the two variables are independent of each other. Change
the value stored in b would not affect the value stored in a.
§ However, if variable is a non-scalar object, such as the following
variable warm:
warm = [1,2,3]
§ what is stored in the variable is the start address of the object
[1,2,3]. The object [1,2,3] is actually stored somewhere
else, not in variable warm. 23
ALIASES
§ When assigning such an non-scalar variable to another variable hot,
hot = warm
§ what is copied to variable hot is not object [1,2,3], rather, it is the
start address of object [1,2,3].
Ø This means both warm and hot contain the same address, which point to the same
object [1,2,3]. We call hot an alias of warm, because they point to the same
object.
Ø change the object pointed to by hot also changing the object pointed by warm. This is
called "side effect".
r
s cala
a
a is bject
o
-
a non
s t
mi jec
war lar ob
sca
6.0001 LECTURE 5 24
CLONING A LIST
§ create a new list and copy every element using
chill = cool[:]
Ø cool[:] is short for cool[0:len(cool)] which returns a copy of cool.
§ After copying, the two variables are independent of each
other: cool still points to the original list, while chill
points to the new list.
6.0001 LECTURE 5 25
SORTING LISTS
§ calling method sort() mutates the list, returns
nothing (None)
§ calling function
sorted()does not
mutate the list, must
assign the result to a
variable
6.0001 LECTURE 5 26
LISTS OF LISTS OF LISTS OF….
§ can have nested lists
§ side effects still
possible after mutation
6.0001 LECTURE 5 27
MUTATION AND ITERATION
§ avoid mutating a list as you are iterating over it
def remove_dups(L1, L2): def remove_dups(L1, L2):
for e in L1: L1_copy = L1[:]
if e in L2: for e in L1_copy:
if e in L2:
[Link](e)
[Link](e)
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
§ L1 is [2,3,4] not [3,4] Why?
• Python uses an internal counter to keep track of index it is in the loop
• mutating changes the list length but Python doesn’t update 28
the counter
6.0001 LECTURE 5
• loop never sees element 2
SUMMARY
§ introduced new compound data types
• tuples
• lists
§ discussed indexing and slicing of tuples and lists
§ discussed iteration over elements of a tuple or list in a for
loop
§ discussed idea of mutability
§ discussed idea of aliasing
§ discussed idea of cloning
ACKNOWLEDGEMENT
• Python Tutor
• Programiz
• MIT OCW