0% found this document useful (0 votes)
141 views26 pages

Tuples, Lists, Aliasing, Mutability, Cloning

This document introduces tuples, lists, aliasing, mutability, and cloning in Python. Tuples are immutable ordered sequences that can contain mixed data types. Lists are mutable ordered sequences that can be changed, with elements accessed by index. Aliasing occurs when multiple names refer to the same object in memory. Mutable objects like lists are impacted by aliasing, as a change via one name affects the other names. Cloning creates a new object to avoid side effects of mutation.

Uploaded by

voduykhoa2504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views26 pages

Tuples, Lists, Aliasing, Mutability, Cloning

This document introduces tuples, lists, aliasing, mutability, and cloning in Python. Tuples are immutable ordered sequences that can contain mixed data types. Lists are mutable ordered sequences that can be changed, with elements accessed by index. Aliasing occurs when multiple names refer to the same object in memory. Mutable objects like lists are impacted by aliasing, as a change via one name affects the other names. Cloning creates a new object to avoid side effects of mutation.

Uploaded by

voduykhoa2504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Tuples, Lists, Aliasing,

Mutability, Cloning
LAST TIME
• Functions
• decomposition – create structure
• abstraction – suppress details
• from now on will be using functions a lot
TODAY
• 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 g s?
st rin
te = () er
b
t = (2, “vgu”, 3) m em
Re le
t[0]  evaluates to 2 tu
p
a
(2, “vgu”, 3) + (5, 6)  evaluates to (2, “vgu”, 3, 5, 6) ans
m e
t[1:2]  slice tuple, evaluates to (“vgu”, ) m a ent
co m el em
t[1:3]  slice tuple, evaluates to (“vgu”, 3) t ra ne
Ex th o
len(t)  evaluates to 3 wi
t[1] = 4  gives error, can’t modify object
When to use tuples
• conveniently used to swap variable values

• used to return more than one value from a function


MANIPULATING TUPLES
LISTS
• ordered sequence of information, accessible by index
• a list is denoted by square brackets, []
• a list contains elements
• usually homogeneous (ie, all integers)
• usually homogeneous (ie, all integers)
• list elements can be changed so a list is mutable
INDICES AND ORDERING
CHANGING ELEMENTS
• lists are mutable!
• assigning to an element at an index changes the value

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


ITERATING OVER A LIST
OPERATIONS ON LISTS - ADD
• add elements to end of list with L.append(element)
• mutates the list!

• 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 object_name.do_something()
• will learn more about these later
OPERATIONS ON LISTS - ADD
• to combine lists together use concatenation, + operator, to give you a
new list
• mutate list with L.extend(some_list)
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
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
OTHER LIST OPERATIONS
• sort() and sorted()
• reverse()
• and many more! https://docs.python.org/3/tutorial/datastructures.html
MUTATION, ALIASING, CLONING
LISTS IN MEMORY
• 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 …

• … all his nicknames refer to old attributes AND all new ones
ALIASES
• hot is an alias for warm – changing one changes the other!
• append() has a side effect
CLONING A LIST
• create a new list and copy every element using
SORTING LISTS
• calling sort() mutates the list, returns nothing
• calling sorted() does not mutate list,
must assign result to a variable
LISTS OF LISTS OF LISTS OF….
• 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

• 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
LIST AND TUPLE COMPREHENSION
NAMED TUPLES - 1
• A way to create simple, lightweight data structures similar to a class,
but without the overhead of defining a full class.
• Like dictionaries, they contain keys that are hashed to a particular
value. On the contrary, it supports both access from key-value and
iteration, the functionality that dictionaries lack.
NAMED TUPLES - 2
# Python code to demonstrate namedtuple()
from collections import namedtuple

# Declaring namedtuple()
Student = namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# Access using index


print("The Student age using index is : ", end="")
print(S[1])

# Access using name


print("The Student name using keyname is : ", end="")
print(S.name)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy