0% found this document useful (0 votes)
91 views

Tuples, Lists, Mutability, Cloning

Tuples are immutable ordered sequences that can contain different element types. Lists are mutable ordered sequences that are similar to tuples but can have their elements changed. While lists allow mutation which makes them more flexible, mutation can also introduce bugs if the same list is referenced in multiple places due to aliasing. Cloning a list creates a copy to avoid these aliasing issues.

Uploaded by

Perry Ho
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Tuples, Lists, Mutability, Cloning

Tuples are immutable ordered sequences that can contain different element types. Lists are mutable ordered sequences that are similar to tuples but can have their elements changed. While lists allow mutation which makes them more flexible, mutation can also introduce bugs if the same list is referenced in multiple places due to aliasing. Cloning a list creates a copy to avoid these aliasing issues.

Uploaded by

Perry Ho
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

TUPLES, LISTS,

MUTABILITY,
CLONING

6.00.1X LECTURE 1
Tuples is an "ordered sequence" of elements which can include different elements within them.

By Ordered Sequence, does not mean elements in sequence are ordered smallest to largest, but that the sequence
itself has an order so that you can get to different parts of the sequence by simply indexing, like strings.

TUPLES
 an ordered sequence of elements, can mix element types
 immutable, cannot change element values
 represented with parentheses
te = () the parentheses help designate that it's a tuple

t = (2,"one",3)
t[0]  evaluates to 2 like strings, we can index this using square brackets

(2,"one",3) + (5,6)  evaluates to (2,"one",3,5,6)


t[1:2]  slice tuple, evaluates to ("one",)
t[1:3]  slice tuple, evaluates to ("one",3)
t[1] = 4  gives error, can’t modify object
6.00.1X LECTURE 2
TUPLES
 conveniently used to swap variable values
x = y temp = x (x, y) = (y, x)
y = x x = y create the tuple with bindings
for x and y by taking the
opposite versions of that tuple.
y = temp allows you to swap variables and return more than one
value from the function
 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) let's us think of tuples as a single construct

(quot, rem) = quotient_and_remainder(4,5)

6.00.1X LECTURE 3
MANIPULATING TUPLES
the tuple consists of tuples aTuple(( ),( ),( ),( ))
 can iterate over tuples

def get_data(aTuple):
nums( )
nums = () nums = empty tuple

words = ()empty tuple words( )


for t in aTuple:
nums = nums + (t[0],) index in the 0 element to get the first integer

if t[1] not in words:


words = words + (t[1],)
min_nums = min(nums)
max_nums = max(nums)
unique_words = len(words)
return (min_nums, max_nums, unique_words)

6.00.1X LECTURE 4
6.00.1X LECTURE 5
Lists have one key difference: they are denoted with square brackets.

LISTS
 ordered sequence of information, accessible by index
 a list is denoted by square brackets, []
 a list contains elements
• usually homogeneous (i.e., all integers)
• can contain mixed types (not common)
 list elements can be changed so a list is mutable
lists can be changed. Can change the
element of a list to be something different.

6.00.1X LECTURE 6
INDICES AND ORDERING
 an element of a list is at a position (aka index) in list, indices start at 0
a_list = []
b_list = [2, 'a', 4, True]
L = [2, 1, 3]
index: 0 1 2
len(L)  evaluates to 3
L[0]  evaluates to 2
L[2]+1  evaluates to 4
L[3]  gives an error
 index can be a variable or expression, must evaluate to an int
i = 2
L[i-1]  evaluates to 1 since L[1] = 1 from above
6.00.1X LECTURE 7
CHANGING ELEMENTS
 lists are mutable!
 assigning to an element at an index changes the value
L = [2, 1, 3]
L[1] = 5
it can change the element within index to 5

 L is now [2, 5, 3], note this is the same object L

[2,5,3]
[2,1,3]

L
6.00.1X LECTURE 8
ITERATING OVER A LIST
 compute the sum of elements of a list
 common pattern
Traditional Way: Can simply iterate over list themselves

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 0 to len(L)-1
• range(n) goes from 0 to n-1

6.00.1X LECTURE 9
6.00.1X LECTURE 10
OPERATIONS ON LISTS - ADD
 add elements to end of list with L.append(element)
append can add something to a list
 mutates the list!
L = [2,1,3] form 3 elements long

L.append(5)  L is now [2,1,3,5] to 4 elements long

 what is the dot?


• lists are Python objects, everything in Python is an object
• objects have data give an object name, the 'dot' says, get out some
method/function associated with that object,
• objects have methods and functions and then call it using ()
• access this information by object_name.do_something()
• will learn more about these later
6.00.1X LECTURE 11
OPERATIONS ON LISTS - ADD
 to combine lists together use concatenation, + operator
 mutate list with L.extend(some_list)

L1 = [2,1,3]
L2 = [4,5,6]
L3 = L1 + L2  L3 is [2,1,3,4,5,6]
L1.extend([0,6])  mutated L1 to [2,1,3,0,6]

Concatenante does not mutate, but extension does.

6.00.1X LECTURE 12
OPERATIONS ON LISTS -
REMOVE
 delete element at a specific index with del(L[index])
 remove element at end of list with L.pop(), returns the
removed element
 remove a specific element with L.remove(element)
• looks for the element and removes it
• if element occurs multiple times, removes first occurrence
• if element not in list, gives an error
L = [2,1,3,6,3,7,0] # do below in order
L.remove(2)  mutates L = [1,3,6,3,7,0]
L.remove(3)  mutates L = [1,6,3,7,0] removes only 1st '3'
del(L[1])  mutates L = [1,3,7,0]
L.pop()  returns 0 and mutates L = [1,3,7]
6.00.1X LECTURE 13
CONVERT LISTS TO STRINGS
AND BACK
 convert string to list with list(s), returns a list with every
character from s an element in L
 can use s.split(), to split a string on a character parameter,
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']
s.split('<')  returns ['I ', '3 cs'] split the string by '<'
L = ['a', 'b', 'c']  L is a list
''.join(L)  returns "abc" conversion of list back into string
'_'.join(L)  returns "a_b_c"
6.00.1X LECTURE 14
OTHER LIST OPERATIONS
 sort() and sorted() two ways to sort a list. Can sort list and return a new version of it, or
we can mutate the list itself.

 reverse()
 and many more!
https://docs.python.org/2/tutorial/datastructures.html

L=[9,6,0,3]
sorted(L)  returns sorted list, does not mutate L
L.sort()  mutates L=[0,3,6,9]
L.reverse()  mutates L=[9,6,3,0]
6.00.1X LECTURE 15
BRINGING TOGETHER LOOPS,
FUNCTIONS, range, and LISTS
 range is a special procedure
 returns something that behaves like a tuple!
 doesn’t generate the elements at once, rather it generates the first
element, and provides an iteration method by which subsequent
elements can be generated
range(5)  equivalent to tuple[0,1,2,3,4]
range(2,6)  equivalent to tuple[2,3,4,5]
range(5,2,-1)  equivalent to tuple[5,4,3]
 when use range in a for loop, what the loop variable iterates over
behaves like a list!
for var in range(5): more convenient to write out range(5) than to list out the entire
<expressions> variable (0, 1, 2, 3, 4)

behind the scenes, gets converted to something that will


behave like:
for var in (0,1,2,3,4):
<expressions>
6.00.1X LECTURE 16
6.00.1X LECTURE 17
Recall: Lists are different from Tuples because they are mutable. However, there are some issues with this.

MUTATION, ALIASING, CLONING

IMPORTANT
and
TRICKY!

Python Tutor is your best friend to help sort this out!


http://www.pythontutor.com/

6.00.1X LECTURE 18
LISTS IN MEMORY
 lists are mutable
 behave differently than immutable types
 is an object in memory
 variable name points to object Lists can have multiple variables pointing to the same list
(i.e. clones). Same instance, but different names for them

 any variable pointing to that object is affected


 key phrase to keep in mind when working with lists is
side effects
If you go an change any element of a list from one name, it will also change the reference from the other name. This will have big side
effects.

6.00.1X LECTURE 19
Justin Drew Bieber
Justin Bieber
AN ANALOGY JB
Bieber
The Bieb
 attributes of a person JBeebs
◦ singer, rich
 he is known by many names
 all nicknames point to the same person
• add new attribute to one nickname …
Justin Bieber: singer, rich , troublemaker
• … all his nicknames refer to old attributes AND all new ones
The Bieb is: singer, rich, troublemaker
JBeebs is: singer, rich, troublemaker
etc…

6.00.1X LECTURE 20
PRINT IS NOT ==
 if two lists print the same thing, does not mean they
are the same structure
 can test by mutating one, and checking
initially looks the same, but they are different

cool = [‘blue’, ‘green’, ‘grey’]


chill = [‘blue’, ‘green’, ‘grey’]
print(cool)
print(chill)

chill[2] = ‘blue’
print(chill)
print(cool)

6.00.1X LECTURE 21
ALIASES
 hot is an alias for warm – changing one changes the
other!
 append() has a side effect

a = 1
b = a
print(a)
print(b)

warm = [‘red’, ‘yellow’, ‘orange’]


this binds "hot" to "warm"
hot = warm

hot.append(‘pink’)
print(hot)
If you change "Hot", you will change "warm" as well
print(warm)

6.00.1X LECTURE 22
CLONING A LIST
 create a new list and copy every element using
chill = cool[:]

The colon [:] makes a copy of cool

cool = [‘blue’, ‘green’, ‘grey’]


chill = cool[:]

chill.append(‘black’)
print(chill)
print(cool)

cloning is really useful when you want to do something with a list that involves mutation, but
don't want to change the original list
6.00.1X LECTURE 23
SORTING LISTS
 calling sort() mutates the list, returns nothing
 calling sorted() does not mutate list, must assign
result to a variable

warm = [‘red’, ‘yellow’, ‘orange’]


sortedwarm = warm.sort()
print(warm)
print(sortedwarm)
no value because sort returns no value
cool = [‘grey’, ‘green’, ‘blue’]
sortedcool = sorted(cool) sorted will not mutate the list
print(cool)
print(sortedcool)

6.00.1X LECTURE 24
LISTS OF LISTS OF LISTS OF….
 can have nested lists (i.e list of lists)

 side effects still possible after mutation

warm = [‘yellow’, ‘orange’]


hot = [‘red’]
brightcolors = [warm]

brightcolors.append(hot)
print(brightcolors)

hot.append(‘pink’)
print(hot)
print(brightcolors)
when you change hot, you will indirectly change brightcolours
print(hot + warm)
print(hot)
6.00.1X LECTURE 25
If you are iterating a list, you want to avoid mutating the list

MUTATION AND ITERATION


 avoid mutating a list as you are iterating over it
def remove_dups(L1, L2): def remove_dups_new(L1, L2):
for e in L1: L1_copy = L1[:]
for e in L1_copy:
if e in L2:
if e in L2:
L1.remove(e) L1.remove(e)

by making a copy, when


L1 = [1, 2, 3, 4] mutating L1, you are iterating
L2 = [1, 2, 5, 6] over something that hasn't
changed because its' pointing to
remove_dups(L1, L2) a different structure

 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 the counter
• loop never sees element 2
6.00.1X LECTURE 26

You might also like