SlideShare a Scribd company logo
1 of 24
TUPLES, LISTS,
ALIASING,
MUTABILITY,
CLONING
6.0001 1
(download slides and .py files and follow
along!)
6.0001 LECTURE 5
LAST
TIME
6.0001 2
 functions
 decomposition – create structure
 abstraction – suppress details
 from now on will be using functions a
lot
TODA
Y
6.0001 3
 have seen variable types: int, float,
bool,string
 introduce new compound data types
• tuples
• lists
 idea of aliasing
 idea of mutability
 idea of cloning
TUPLES
 an ordered sequence of elements, can mix element
types
 cannot change element values, immutable
 represented with parentheses
te = ()
t = (2,"mit",3)
t[0]
(2,"mit",3) + (5,6)
 evaluates to 2
 evaluates to
(2,"mit",3,5,6)
t[1:2]
t[1:3]
len(t)
 slice tuple, evaluates to
("mit",)
 slice tuple, evaluates to
("mit",3)
 evaluates to 3
t[1] = 4  gives error, can’t modify
object 6.0001 4
TUPLES
 conveniently used to swap variable
values
x = y
y = x
temp = x
x = y
y = temp
(x, y) = (y, x)
 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)
(quot, rem) = quotient_and_remainder(4,5)
6.0001 5
MANIPULATING
TUPLES
 can iterate over
tuples
def get_data(aTuple):
nums = ()
words = ()
for t in aTuple:
nums = nums + (t[0],)
if t[1] not in words:
words = words + (t[1],)
min_n = min(nums)
max_n = max(nums)
unique_words = len(words)
return (min_n, max_n, unique_words)
aTuple:(( ),( ),( ))
nums( )
words( ? ? ? )
if not already in words
i.e. unique strings from aTuple
6.0001 6
LIS
TS
6.0001 7
 ordered sequence of information, accessible by
index
 a list is denoted by square brackets, []
 a list contains elements
• usually homogeneous (ie, all integers)
• can contain mixed types (not common)
 list elements can be changed so a list is mutable
INDICES AND
ORDERING
a_list = []
L = [2, 'a', 4, [1,2]]
len(L)  evaluates to
4
L[0]  evaluates to
2
L[2]+1  evaluates to
5
L[3]
L[4]
i = 2
L[i-1]
 evaluates to [1,2], another list!
 gives an error
 evaluates to ‘a’ since L[1]='a'
above 6.0001 8
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
L
[2,5,3]
6.0001 9
ITERATING OVER A LIST
 compute the sum of elements of a list
 common pattern, iterate over list
elements
total = 0
for i in range(len(L)):
total += L[i]
print total
 notice
• list elements are indexed
0
to len(L)-1
• range(n) goes from 0 to n-
1
total = 0
for i in L:
total += i
print total
6.0001 10
OPERATIONS ON LISTS
- ADD
 add elements to end of list with
L.append(element)
 mutates the list!
L = [2,1,3]
L.append(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 and functions
• access this information by
6.0001 11
OPERATIONS ON LISTS -
ADD
6.0001 12
 to combine lists together use concatenation, +
operator, to give you a new list
 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, L2 unchanged
L1.extend([0,6])  mutated L1 to
[2,1,3,0,6]
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]
del(L[1])
L.pop()
 mutates L = [1,3,7,0]
 returns 0 and mutates L =
[1,3,7]
6.0001 13
CONVERT LISTS TO
STRINGS AND BACK
6.0001 14
 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"
list(s)
s.split('<')
L = ['a','b','c']
''.join(L)
'_'.join(L)
 s is a string
 returns ['I','<','3','
','c','s']
 returns ['I', '3 cs']
 L is a list
 returns "abc"
 returns "a_b_c"
OTHER LIST
OPERATIONS
6.0001 15
 sort() and sorted()
 reverse()
 and many more!
https://docs.python.org/3/tutorial/datastructures.ht
ml
L=[9,6,0,3]
sorted(L)
L.sort()
L.reverse()
 returns sorted list, does not
mutate L
 mutates L=[0,3,6,9]
 mutates L=[9,6,3,0]
MUTATION, ALIASING,
CLONING
IMPORTANT
and
TRICK
Y!
Again, Python Tutor is your best
friend to help sort this out!
http://www.pythontutor.com/
6.0001 16
LISTS IN
MEMORY
6.0001 17
 lists are mutable
 behave differently than immutable types
 is an object in memory
 variable name points to object
 any variable pointing to that object is affected
 key phrase to keep in mind when working with
lists is
side effects
AN
ANALOGY
 attributes of a person
◦ 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 singer rich
troublemaker JBeebs singer rich
troublemaker 6.0001 18
ALIAS
ES
 hot is an alias for warm – changing one
changes the other!
 append() has a side effect
6.0001 19
CLONING A
LIST
 create a new list and copy every element
using
chill = cool[:]
6.0001 20
SORTING
LISTS
 calling sort() mutates the list, returns
nothing
 calling
sorted() does
not mutate list,
must assign result
to a variable
6.0001 21
LISTS OF LISTS OF LISTS
OF….
6.0001 22
 can have nested
lists
 side effects still
possible after
mutation
MUTATION AND
ITERATION
Try this in Python Tutor!
 avoid mutating a list as you are iterating
over it
def remove_dups(L1, L2):
for e in L1:
if e in L2:
L1.remove(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 the
counter
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
L1.remove(e)
6.0001 23
MIT OpenCourseWare
https://ocw.mit.edu
6.0001 Introduction to Computer Science and Programming in Python
Fall 2016
For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms.

More Related Content

Similar to White paper on tuples

Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfPython-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Meha46
 

Similar to White paper on tuples (20)

Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Python list manipulation basics in detail.pdf
Python list  manipulation basics in detail.pdfPython list  manipulation basics in detail.pdf
Python list manipulation basics in detail.pdf
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python lists
Python listsPython lists
Python lists
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Introduction of Python-1.pdf
Introduction of Python-1.pdfIntroduction of Python-1.pdf
Introduction of Python-1.pdf
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfPython-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

White paper on tuples

  • 1. TUPLES, LISTS, ALIASING, MUTABILITY, CLONING 6.0001 1 (download slides and .py files and follow along!) 6.0001 LECTURE 5
  • 2. LAST TIME 6.0001 2  functions  decomposition – create structure  abstraction – suppress details  from now on will be using functions a lot
  • 3. TODA Y 6.0001 3  have seen variable types: int, float, bool,string  introduce new compound data types • tuples • lists  idea of aliasing  idea of mutability  idea of cloning
  • 4. TUPLES  an ordered sequence of elements, can mix element types  cannot change element values, immutable  represented with parentheses te = () t = (2,"mit",3) t[0] (2,"mit",3) + (5,6)  evaluates to 2  evaluates to (2,"mit",3,5,6) t[1:2] t[1:3] len(t)  slice tuple, evaluates to ("mit",)  slice tuple, evaluates to ("mit",3)  evaluates to 3 t[1] = 4  gives error, can’t modify object 6.0001 4
  • 5. TUPLES  conveniently used to swap variable values x = y y = x temp = x x = y y = temp (x, y) = (y, x)  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) (quot, rem) = quotient_and_remainder(4,5) 6.0001 5
  • 6. MANIPULATING TUPLES  can iterate over tuples def get_data(aTuple): nums = () words = () for t in aTuple: nums = nums + (t[0],) if t[1] not in words: words = words + (t[1],) min_n = min(nums) max_n = max(nums) unique_words = len(words) return (min_n, max_n, unique_words) aTuple:(( ),( ),( )) nums( ) words( ? ? ? ) if not already in words i.e. unique strings from aTuple 6.0001 6
  • 7. LIS TS 6.0001 7  ordered sequence of information, accessible by index  a list is denoted by square brackets, []  a list contains elements • usually homogeneous (ie, all integers) • can contain mixed types (not common)  list elements can be changed so a list is mutable
  • 8. INDICES AND ORDERING a_list = [] L = [2, 'a', 4, [1,2]] len(L)  evaluates to 4 L[0]  evaluates to 2 L[2]+1  evaluates to 5 L[3] L[4] i = 2 L[i-1]  evaluates to [1,2], another list!  gives an error  evaluates to ‘a’ since L[1]='a' above 6.0001 8
  • 9. 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 L [2,5,3] 6.0001 9
  • 10. ITERATING OVER A LIST  compute the sum of elements of a list  common pattern, iterate over list elements total = 0 for i in range(len(L)): total += L[i] print total  notice • list elements are indexed 0 to len(L)-1 • range(n) goes from 0 to n- 1 total = 0 for i in L: total += i print total 6.0001 10
  • 11. OPERATIONS ON LISTS - ADD  add elements to end of list with L.append(element)  mutates the list! L = [2,1,3] L.append(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 and functions • access this information by 6.0001 11
  • 12. OPERATIONS ON LISTS - ADD 6.0001 12  to combine lists together use concatenation, + operator, to give you a new list  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, L2 unchanged L1.extend([0,6])  mutated L1 to [2,1,3,0,6]
  • 13. 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] del(L[1]) L.pop()  mutates L = [1,3,7,0]  returns 0 and mutates L = [1,3,7] 6.0001 13
  • 14. CONVERT LISTS TO STRINGS AND BACK 6.0001 14  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" list(s) s.split('<') L = ['a','b','c'] ''.join(L) '_'.join(L)  s is a string  returns ['I','<','3',' ','c','s']  returns ['I', '3 cs']  L is a list  returns "abc"  returns "a_b_c"
  • 15. OTHER LIST OPERATIONS 6.0001 15  sort() and sorted()  reverse()  and many more! https://docs.python.org/3/tutorial/datastructures.ht ml L=[9,6,0,3] sorted(L) L.sort() L.reverse()  returns sorted list, does not mutate L  mutates L=[0,3,6,9]  mutates L=[9,6,3,0]
  • 16. MUTATION, ALIASING, CLONING IMPORTANT and TRICK Y! Again, Python Tutor is your best friend to help sort this out! http://www.pythontutor.com/ 6.0001 16
  • 17. LISTS IN MEMORY 6.0001 17  lists are mutable  behave differently than immutable types  is an object in memory  variable name points to object  any variable pointing to that object is affected  key phrase to keep in mind when working with lists is side effects
  • 18. AN ANALOGY  attributes of a person ◦ 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 singer rich troublemaker JBeebs singer rich troublemaker 6.0001 18
  • 19. ALIAS ES  hot is an alias for warm – changing one changes the other!  append() has a side effect 6.0001 19
  • 20. CLONING A LIST  create a new list and copy every element using chill = cool[:] 6.0001 20
  • 21. SORTING LISTS  calling sort() mutates the list, returns nothing  calling sorted() does not mutate list, must assign result to a variable 6.0001 21
  • 22. LISTS OF LISTS OF LISTS OF…. 6.0001 22  can have nested lists  side effects still possible after mutation
  • 23. MUTATION AND ITERATION Try this in Python Tutor!  avoid mutating a list as you are iterating over it def remove_dups(L1, L2): for e in L1: if e in L2: L1.remove(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 the counter def remove_dups(L1, L2): L1_copy = L1[:] for e in L1_copy: if e in L2: L1.remove(e) 6.0001 23
  • 24. MIT OpenCourseWare https://ocw.mit.edu 6.0001 Introduction to Computer Science and Programming in Python Fall 2016 For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms.