0% found this document useful (0 votes)
9 views119 pages

Python Sequence Types and Containers

The document provides an overview of sequence types in Python, including lists, tuples, sets, dictionaries, and strings, highlighting their characteristics such as mutability and how they can be iterated. It discusses various operations and methods associated with these data structures, including list comprehensions, sorting, and copying techniques. Additionally, it explains the differences between the sort() and sorted() functions, emphasizing their impact on the original list and memory usage.

Uploaded by

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

Python Sequence Types and Containers

The document provides an overview of sequence types in Python, including lists, tuples, sets, dictionaries, and strings, highlighting their characteristics such as mutability and how they can be iterated. It discusses various operations and methods associated with these data structures, including list comprehensions, sorting, and copying techniques. Additionally, it explains the differences between the sort() and sorted() functions, emphasizing their impact on the original list and memory usage.

Uploaded by

23130307
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FACULTY OF INFORMATION TECHNOLOGY

Semester 1, 2025/2026
2
 List

 Range

 Set

 Tuple

 Dictionary

Py – NLU 3
 What is sequence type?
◦ A sequence type is a type that holds a sequence of elements.
 Sequence types in Python
List - Sequence of elements enclosed in square brackets : [ ]

Tuple - Sequence of elements enclosed in parenthesis : ( )

Set - Sequence of elements enclosed in curly braces : { }

Dictionary - Sequence of elements enclosed in curly braces : { } : each element is a pair

String - Sequence of characters, digits, or any symbols enclosed in quotes : “ ” | ‘ ‘

Elements of a sequence are separated by using comma and elements may of different data type

Py – NLU 4
 What is sequence type?
◦ A sequence type is a type that holds a sequence of elements.
 Sequence types in Python

Mutable Immutable
List Tuple
String
Set

Dictionary

Py – NLU 5
Lists, tuples, dictionaries, and sets are all iterable objects.
 Any Python object capable of returning its members one at
a time, permitting it to be iterated over in a for-loop.
 Functions act on iterables:
◦ list, tuple, dict, set: construct a list, tuple, dictionary, or set,
respectively, from the contents of an iterable
◦ sum: sum the contents of an iterable.
◦ sorted: return a list of the sorted contents of an iterable
◦ any: returns True and ends the iteration immediately
if bool(item) was True for any item in the iterable.
◦ all: returns True only if bool(item) was True for all items in the
iterable.
◦ max: return the largest value in an iterable.
◦ min: return the smallest value in an iterable.
Py – NLU 6
 The built-in enumerate function allows us to iterate over an
iterable, while keeping track of the iteration count:

# basic usage of `enumerate`


for entry in enumerate("FIT NLU"): (0, 'F')
print(entry) (1, 'I')
(2, 'T')
(3, ' ')
(4, 'N')
(5, 'L')
(6, 'U')

Py – NLU 7
 an object that manages an iteration through a series of values
 Lists, tuples, dictionaries, and sets are all iterable objects
 Method iter(): use to get an iterator
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit)) apple
print(next(myit)) banana
cherry

strings are iterable objects?


Py – NLU 8
 An object that holds and organizes other objects (like
variables or data).

 Python provides several built-in container types, including:


◦ List (list): An ordered and mutable collection.

◦ Tuple (tuple): An ordered but immutable collection.

◦ Dictionary (dict): A collection of key-value pairs.

◦ Set (set): An unordered collection of unique elements.

◦ Frozen Set (frozenset): An immutable version of a set.

Py – NLU 9
 Strings are containers? fit_string = "FIT NLU"
print(fit_string[1])

# slicing
print(fit_string[1:4])

# iteration
for char in fit_string:
print(char)

# update string
my_string = "hello"
my_string[0] = 'H' # ?
Py – NLU 10
 A summary of built-in containers in Python

Container

access order duplicate mutability

no
index key yes no yes no yes no
access

list, list, dict, list, tuple, list, dict, tuple


dict set set
tuple tuple set dict set
Py – NLU 11
 Used to store multiple items in a single variable
 Identical to dynamically scaled arrays defined in other
languages, such as Array List in Java and Vector in C++
 Items in a List is separated by commas and denoted by the
symbol []
 Example: lst = ['a', 'b', 'c', 'd']

Py – NLU 12
 Homogeneous list:
◦ A list in which all the items belong to the same data type
◦ i.e., even= [2,4,6,8,10]

 Non-Homogeneous list
◦ A list in which the items belong to different data types.
◦ i.e., employee= [‘John’, 22, ‘Sales’, 20000]

Py – NLU 13
 Example: list= [50, 70, 30, 20, 90, 10, 50]
 Indexing in a Python list starts from 0.
 Indexes of elements in the list:

Py – NLU 14
 lst = [] - create an empty list
 lst = [1, 2, 3] - create a list with data in it
 [Link](value) - add value to the end of a list, increasing the list's
length by 1. Of all the list functions, this one is used the most.
 len(lst) - access length of a list
 lst[0] - access individual elements with square brackets and int index
 for <<var>> in lst: - loop over a list. On each iteration of the loop,
Python points the variable var to the next element
 <<value >> in lst - boolean test if value is in lst (just like for string)

Py – NLU 15
 +: similar to the extend()
 += Error: List + and += only add a lists of elements, not a
single element (raise error)
 pop(): remove the element at position pos and return it.
Default pos=-1
 remove(elem): search the list for the first instance of elem and
remove it (error if elem not found in the list)

Py – NLU 16
 index(x): look for first instance of x in list and return its
index. Raises an error if x is not in there

 insert(index, x): insert the element x so it is at the given


index, shifting elements towards the end of the list as needed.

 copy(): returns a copy of lst, a new list populated with


elements from the original list

Py – NLU 17
 reverse(): reverses the order of the list
 append(): Adds an element at the end of the list
 clear(): Removes all the elements from the list
 count():Returns the number of elements with the specified
value
 extend(): Add the elements of a list (or any iterable), to the
end of the current list
 sort(): sorts the list

Py – NLU 18
 List copy is shallow or deep copy?
import copy

original_list = [1, 2, 3, 4]
list_copy = original_list.copy()

# Modify an element inside a copy list


list_copy[0] = 100

# Output: ?
print("Original list:", original_list)
print("List copy:", list_copy)
# Output:?
Py – NLU 19
 List copy is shallow or deep copy?
import copy

original_list = [1, 2, 3, 4]
list_copy = [Link](original_list)

# Modify an element inside a copy list


list_copy[0] = 100

# Output: ?
print("Original list:", original_list)
print("List copy:", list_copy)# Output: ?

Py – NLU 20
 sorted(): orders the elements into increasing order. The
elements can be any type (str, int, float, ..) supporting < and
==
 Sort Upper / Lower: uppercase chars come before lowercase
chars, so uppercase strings will sort to the front of the list
sorted(['donut', 'ZEBRA', 'BANANA', 'apple'])
 min(lst), max(lst): return the smallest or largest element in lst
 sum(lst): returns the arithmetic sum of a collection numbers

Py – NLU 21
 Syntax: lst[start : end : step]

where,

◦ start – index position from where the slicing will start in a list

◦ stop – index position till which the slicing will end in a list

◦ step – number of steps, i.e. the start index is changed after every n
steps, and list slicing is performed on that index

Py – NLU 22
 Syntax: lst[start : end : step]
 Example:

Py – NLU 23
 Examples:
my_list = [1, 3, 5, 7, 9]

print('Items in List are:', my_list[:])


print('Items in List after 3rd position are:',
my_list[3:])
print('Items in List till 4th index are:',
my_list[:4])
print('Items in List from 1st to 6th index
are:', my_list[1:6])
print('Items in List at step of 2 are:',
my_list[::2])
print('Items in List are:', my_list[::-2])

Py – NLU 24
 Loop through the list items using for loop
 Loop through the list items by referring to their index number

lst = ["DH22DTA", "DH22DTB", "DH22DTB"]


for x in lst:
print(x)

for i in range(len(lst)):
print(lst[i])

Py – NLU 25
 Loop through the list items by using a while loop
 List Comprehension offers the shortest syntax for looping
through lists

lst = ["DH22DTA", "DH22DTB", "DH22DTB"]

i = 0
while i < len(thislist):# use while loop
print(thislist[i])
i = i + 1
# use list comprehension
[print(x) for x in lst]
Py – NLU 26
 List comprehensions provide a concise way to create lists
 Syntax: newList = [newlist = [expression for item in iterable if condition ==
True]]
 Parameter:
◦ expression: Represents the operation you want to execute on every item within the
iterable.
◦ element: The term “variable” refers to each value taken from the iterable.
◦ iterable: specify the sequence of elements you want to iterate through.(e.g., a list,
tuple, or string).
◦ condition: (Optional) A filter helps decide whether or not an element should be
added to the new list.

Py – NLU 27
 Examples:
lst = ["apple", "banana", "cherry", "kiwi",
"mango"]

with_out_apple_list = [x for x in lst if x


!= "apple"]

less_than_5_list = [x for x in range(10) if


x < 5]
upper_case_list = [[Link]() for x in lst]

print(with_out_apple_list)
print(less_than_5_list)
print(upper_case_list)
Py – NLU 28
 The initial expression in a list comprehension can be any
arbitrary expression, including another list comprehension.
 Syntax: new_list = [[expression for item in list]
for item in list]
 Example:

matrix =[[x for x in range(3)] for y in range(3)]


print(matrix)

Py – NLU 29
 Syntax: [Link](reverse, key)

 Parameters:
◦ reverse - By default False. If True is passed, the list is sorted in
descending order.

◦ key - Comparion is based on this function.

Py – NLU 30
 List objects have a sort() method that will sort the list
alphanumerically, ascending (default)
◦ in-place sort

fruits = ["orange", "mango", "kiwi",


"pineapple", "banana"]

[Link]()
print(fruits)
# reverse order
[Link](reverse = True)
print(fruits)

Py – NLU 31
 List objects have a sort() method that will sort the list
alphanumerically, ascending (default)
◦ in-place sort

fruits = ["orange", "mango", "kiwi",


"Pineapple", "banana"]

[Link]()
print(fruits)
# case-insensitive
[Link](key = [Link])
print(fruits)

Py – NLU 32
 Both [Link]() and sorted() have a key parameter to specify a
function to be called on each list element prior to making
comparisons.

def func(x):
return x % 7

numbers = [15, 3, 11, 7]

print("Normal sort :", sorted(numbers))


print("Sorted with key:", sorted(numbers,
key=func))

Py – NLU 33
 Syntax: sorted(iterable,reverse=...,key=...)

Parameter Description
iterable Required. The sequence to sort, list,
dictionary, tuple etc.
key Optional. A Function to execute to decide
the order. Default is None
reverse Optional. A Boolean. False will sort
ascending, True will sort descending.
Default is False

Py – NLU 34
 The main differences:
◦ sort(): has no return value and directly modifies the original list,
changing the order of the elements contained in it ➔ mutable

◦ sorted(): has a return value, which is a sorted copy of the original list,
the original list remains intact ➔ immutable

Py – NLU 35
 Examples:
#original list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]
#sort original list in default ascending order
my_numbers_sorted = sorted(my_numbers)
#print original list
print(my_numbers)
#print the copy of the original list that was
created
print(my_numbers_sorted)
my_numbers.sort()
#print original list
print(my_numbers)

Py – NLU 36
 Data type:
◦ sort(): only used on lists
◦ sorted(): used on any iterable, such as lists, tuples, strings, or
generators
 Keep original order of the list:
◦ sorted(): create a new sorted list with list elements sorted in the
desired order.
◦ sort(): the original list will be altered and the original order will be lost
 Working with larger data sets:
◦ sort() takes up and consumes less memory since it just sorts the list
in-place and creates no unncessary new list that you don't need
Py – NLU 37
 Using = operator
lst = ["apple", "banana", "cherry"]
lst1 = lst Deep or
lst1[0] = "APPLE" Shallow
copy?
print(lst)

 Using the built-in List method copy()


lst = ["apple", "banana", "cherry"] Deep or
lst1 = [Link]() Shallow
lst1[0] = "APPLE" copy?
print(lst)

Py – NLU 38
 Use the list() method
lst = ["apple", "banana", "cherry"]
lst1 = list(lst) Deep or
lst1[0] = "APPLE" Shallow
copy?
print(lst)

 Use the slice Operator


lst = ["apple", "banana", "cherry"]
lst1 = lst[:] Deep or
lst1[0] = "APPLE" Shallow
copy?
print(lst)
Py – NLU 39
 Using the + operator
 Using append() method to append all the items from the first
list into the second list
 Using the extend() method
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2 # use + operator
list4 = [4, 5, 6]
for x in list2:
[Link](x)
[Link](list4)# in-place

Py – NLU 40
Operation Average Case Worst Case
Copy O(n) O(n)
Append[1] O(1) O(1)
Pop last O(1) O(1)
Pop intermediate O(k) O(k)
Insert O(n) O(n)
Get Item O(1) O(1)
Set Item O(1) O(1)
Delete Item O(n) O(n)
Iteration O(n) O(n)

'n' is the number of elements currently in the container.


'k' is either the value of a parameter orPy
the– number
NLU of elements in the parameter 41
Operation Average Case Worst Case
Get Slice O(k) O(k)
Del Slice O(n) O(n)
Set Slice O(k+n) O(k+n)
Extend[1] O(k) O(k)
Sort O(n log n) O(n log n)
Multiply O(nk) O(nk)
x in s O(n) O(n)
min(s), max(s) O(n) O(n)
Get Length O(1) O(1)

'n' is the number of elements currently in the container.


'k' is either the value of a parameter orPy
the– number
NLU of elements in the parameter 42
43
 range() function generates a sequence of numbers
◦ returns an immutable sequence of numbers
◦ mainly used when working with for loops
 Syntax: range(start, stop, step)
Where,
◦ Start: (optional) starting value from start
◦ Stop: (required) ending up to stop (non-inclusive)
◦ Step: (optional) "step" amount between numbers, must not be zero

Py – NLU 44
 range(stop): returns a sequence of numbers starting from 0,
incrementing by 1, and ending at the stop (non-inclusive)
 range(start, stop): generates a sequence of numbers based on
the start (inclusive) and stop (non-inclusive) values that
increment by 1
 range(start, stop, step): generates a sequence of numbers that
starts counting at start (inclusive) and increments according
to step until it reaches stop (non-inclusive)
 reversed(): takes in a linear collection and returns a reversed
form of it (a variation of range)

Py – NLU 45
 More detail:

Py – NLU 46
 Examples:
for num in range(5):# use only stop
print(num)

for num in range(5,11):# use start and stop


print(num)

for num in range(10, 21, 2): # use start, stop, step


print(num)

s = 'Python'
list(reversed(range(len(s))))

Py – NLU 47
48
 A collection of unique elements
x = {<obj>, <obj>, ..., <obj>}

 A collection is unordered, unchangeable*, and unindexed.


 Creating sets by placing all the elements inside curly braces {},
separated by commas (,)
 Using set() constructor to make a set
 Set items can be of any data type
my_set1 = set(("apple", "banana", "cherry"))
my_set2 = {"apple", "banana", "cherry"}

* Note: Set items are unchangeable, but you can remove items and add new items.
Py – NLU 49
 A set of built-in methods on sets

Method Shortcut Description


add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() - Returns a set containing the difference
between two or more sets
difference_update() -= Removes the items in this set that are also
included in another, specified set
discard() Remove the specified item
intersection() & Returns a set, that is the intersection of two
other sets

Py – NLU 50
 a set of built-in methods on sets
Method Shortcut Description
intersection_update() &= Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not

issubset() <= Returns whether another set contains this set or not

< Returns whether all items in this set is present in


other, specified set(s)
issuperset() >= Returns whether this set contains another set or not

> Returns whether all items in other, specified set(s) is


present in this set
pop() Removes an element from the set
Py – NLU 51
 A set of built-in methods on sets

Method Shortcut Description


remove() Removes the specified element
symmetric_difference() ^ Returns a set with the symmetric
differences of two sets
symmetric_difference_update() ^= Inserts the symmetric differences from this
set and another
union() | Return a set containing the union of sets
update() |= Update the set with the union of this set
and others

Py – NLU 52
 Cannot access items in a set by referring to an index or a key:

my_set1 = set(("apple", "banana", "cherry"))


for x in my_set1:
print(x)

 Check the existing of an item in a given set:

print("banana" in my_set1)

Py – NLU 53
 Several ways to join two or more sets

 The union() method joins all items from both sets (or using |
operator instead of union())

 Syntax:

[Link](x2[, x3 ...])

x1 | x2 [| x3 ...]

Py – NLU 54
 Several ways to join two or more sets

 Using union() or | to join multiple sets

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}
set3 = {"apple", "bananas", "cherry"}

myset1 = [Link](set2, set3)


myset2 = set1 | set2 | set3

Py – NLU 55
 Several ways to join two or more sets

 Using update() method inserts all items from one set into
another → changes the original set, and does not return a new
set

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

[Link](set2)

Py – NLU 56
 Keep ONLY the duplicates

 The intersection() method will return a new set, that only


contains the items that are present in both sets.

 Syntax:

[Link](x2[, x3 ...])

x1 & x2 [& x3 ...]

Py – NLU 57
 Using intersection() or & to the set of elements common to
both sets

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = [Link](set2)
set4 = set1 & set2

Py – NLU 58
 The intersection_update() method will also keep ONLY the
duplicates ➔ change the original set instead of returning a
new set

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.intersection_update(set2)
print(set1)# ?

Py – NLU 59
 The difference will return a new set that will contain only the
items from the first set that are not present in the other set.

 Syntax:

[Link](x2[, x3 ...])

x1 - x2 [- x3 ...]

Py – NLU 60
 The - operator instead of the difference() method to compute
the difference between two or more sets

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = [Link](set2)
set4 = set1 - set2

Py – NLU 61
 The difference_update() method will also keep the items from
the first set that are not in the other set ➔ change the original
set instead of returning a new set.

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.difference_update(set2)

print(set1)

Py – NLU 62
 The symmetric_difference() (or ^ operator) method will keep
only the elements that are NOT present in both sets

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1.symmetric_difference(set2)

print(set3)

Py – NLU 63
 The symmetric_difference_update() method will also keep all
but the duplicates ➔ change the original set instead of
returning a new set.

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.symmetric_difference_update(set2)

print(set1)

Py – NLU 64
 frozenset(): creates an immutable Set object from an iterable
 Syntax: frozenset(iterable_object_name)
◦ Parameter : iterable_object_name
◦ Return : Returns an equivalent frozenset object.

Frozen set objects are


immutable and can not be
modified after the creation

Py – NLU 65
66
 A tuple is like a list but written within parenthesis
numbers = (1, 2, -5)
str_tuple = ("apple",)
t2 = 1, 2, 3 # works without parens
 Tuple Characteristics:
◦ Ordered: maintain the order of elements
◦ Immutable: cannot be changed after creation (cannot change, add or
remove items after the tuple has been created)
◦ Allow duplicates: can contain duplicate values

Py – NLU 67
 Constructor: tuple()
 Access tuple items by referring to the index number,
numbers[0]
 Negative indexing means start from the end
 Range of indexes: the return value will be a new tuple with the
specified items, numbers[1:4]
 Check if Item Exists: determine if a specified item is present in
a tuple use the in keyword

if 10 in numbers:

Py – NLU 68
 Two built-in methods on tuples

Method Description
count() Returns the number of times a specified value occurs in a
tuple
index() Searches the tuple for a specified value and returns the
position of where it was found

Py – NLU 69
 In some cases, a function can return 2 or more values

def min_max_avg(numbers):
if not numbers: #Check empty list
return None, None, None

minimum = min(numbers)
maximum = max(numbers)
average = sum(numbers) / len(numbers)
return minimum, maximum, average

Py – NLU 70
 Using for loop
my_tuple = ("apple", "banana", "cherry")
for x in my_tuple:
print(x)

for i in range(len(thistuple)): # range, len


print(my_tuple[i])

 Using a while loop

while i < len(my_tuple):


print(my_tuple[i])
i = i + 1

Py – NLU 71
 Using + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

 Using * to multiply the content of a tuple a given number of


times

tuple4 = tuple1 * 2
print(tuple4)

Py – NLU 72
 Using sort() method?

 Using sorted() method as with strings?

tpl1 = (3, 1, 4, 5, 2) tpl1 = (3, 1, 4, 5, 2)

print([Link]()) l_sorted = sorted(tpl1)


print(l_sorted)
AttributeError: 'tuple' object has no attribute 'sort' print(tpl1)
sorted() returns a sorted list when a tuple is passed.

Py – NLU 73
74
 Used to store data values in key:value pairs.
 A collection which is ordered (from version 3.7), changeable
and do not allow duplicates
 Syntax:
my_dict = {
key1: value1,
key2: value2,
key3: value3,
…,
keyn: valuen
}
Py – NLU 75
 Example:

d = {} # Create empty dict


d['ca'] = 'California' # 1. Set key/value
pairs into dict
d['ok'] = 'Oklahoma'
d['nj'] = 'New Jersey'
d['tx'] = 'Texas'
val = d['nj'] # 2. Retrieve value by key
val = d['xx'] # fails with KeyError
check = 'nj' in d # 3. in check -> True

Py – NLU 76
 Example:

Py – NLU 77
 len(d): get the number of key/value pairs in the dict

 [Link](key): retrieves the value for a key, but if the key is not
there, returns None by default.

◦ [Link](key, missing-value) similar to getOrDefault in Java Map.

 [Link](): returns an iterable of all the keys in dict

 [Link](): returns an iterable of all the values in dict.

 [Link](): returns an iterable of the key,value pairs.

Py – NLU 78
 Accessing item: x = d[“ca"]

 Check if Key Exists:


my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in my_dict:
print("Yes, it is in the dict")

Py – NLU 79
 Change Values: my_dict["year"] = 2018

 Update dict: my_dict.update({"year": 2020})

 Adding an item: my_dict["color"] = "red"

◦ Can use my_dict.update["color"] = "red" if color is a new key

Py – NLU 80
 Remove an item: my_dict.pop("model")

 Removes the last inserted item: my_dict.popitem()

 Removes the item with a given key name: del my_dict["model"]

 Delete the dictionary: del my_dict

 Empty the dictionary: my_dict.clear()

Py – NLU 81
 Using a for loop
for x in my_dict:
print(x) # Print all keys

for x in my_dict:
print(my_dict[x]) # Print all values

for x in my_dict.values():
print(x) # Print all values

Py – NLU 82
 Using a for loop

for x in my_dict.keys():
print(x) # print all keys

for key, value in my_dict.items():


print(key, value) # Print all pair key:value

Py – NLU 83
 Using = operator
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
copy_dict = my_dict
copy_dict["year"] = 2024

print(my_dict["year"])# 1964 or 2024?


Deep or
Shallow
copy?
Py – NLU 84
 Using the built-in Dictionary method copy()

my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
copy_dict = my_dict.copy()
copy_dict["year"] = 2024

print(my_dict["year"])# 1964 or 2024? Deep or


Shallow
copy?
Py – NLU 85
 Use the dict() method

my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
copy_dict = dict(my_dict)
copy_dict["year"] = 2024

print(my_dict["year"])# 1964 or 2024?


Deep or
Shallow
copy?
Py – NLU 86
 A dictionary can contain dictionaries
dh22dt = {
"dh22dta" : {
"name" : "DH22DTA",
"quantity": 100
},
"dh22dtb" : {
"name" : "DH22DTB",
"quantity": 110
},
"dh22dtc" : {
"name" : "DH22DTC",
"quantity": 109
}
} Py – NLU 87
-keys- -nested keys- -value set 1-

dh22dta name DH22DTA

dh22dtb quantity 100

dh22dtc

-nested keys- -value set 3- -nested keys- -value set 2-

name DH22DTC name DH22DTB

quantity 109 quantity 110

Py – NLU 88
 A dictionary can contain dictionaries
dh22dta = {
"name" : "DH22DTA",
"quantity": 100
} dh22dt = {
dh22dtb = { "dh22dta" : dh22dta,
"name" : "DH22DTB", "dh22dtb" : dh22dtb,
"quantity": 110 "dh22dtc" : dh22dtc
} }
dh22dtc = {
"name" : "DH22DTC",
"quantity": 109
}

Py – NLU 89
 Access Items in Nested Dictionaries: use the name of the
dictionaries, starting with the outer dictionary
◦ i.e., to get the quantity of dh22dta class:
dh22dt["dh22dta"]["quantity"]
 Loop Through Nested Dictionaries: using the items() method

for x, obj in [Link]():


print(x)

for y in obj:
print(y + ':', obj[y])

Py – NLU 90
 A set of built-in methods on dictionaries
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Py – NLU 91
# list of integers # tuple of integers
lst1 = [1, 2, 3, 4, 5, 6] tpl1 = (1, 2, 3, 4, 5, 6)

# list of mixed types # tuple of mixed types


lst2 = [1, 2, 3, 'FIT', 5, 'NLU', 5.6] tpl2 = (1, 2, 3, 'FIT', 5, 'NLU', 5.6)

# list included list # tuple included list


lst3 = [1, 2, 3, 'FIT', 5, [1, 2, 3], 5.6] tpl3 = (1, 2, 3, 'FIT', 5, [1, 2, 3], 5.6)

# list included set # tuple included set


lst4 = [1, 2, 3, 'FIT', 5, {1, 2, 3}, 5.6] tpl4 = (1, 2, 3, 'FIT', 5, {1, 2, 3}, 5.6)

# list included tuple # tuple included tuple


lst5 = [1, 2, 3, 'FIT', 5, (1, 2, 3), 5.6] tpl5 = (1, 2, 3, 'FIT', 5, (1, 2, 3), 5.6)
Py – NLU 92
# set of integers
st1 = {1, 2, 3, 4, 5, 6}

# set of mixed types


st2 = {1, 2, 3, 'FIT', 5, 'NLU', 5.6} st1 = {1, 2, 3, 4, 5, 6}
lst = ['a', 'b', 'c']
# set included list [Link](lst)
st3 = {1, 2, 3, 'FIT', 5, [1, 2, 3], 5.6}
print(st1)
# set included set
st4 = {1, 2, 3, 'FIT', 5, {1, 2, 3}, 5.6}

# set included tuple


st5 = {1, 2, 3, 'FIT', 5, (1, 2, 3), 5.6}
Py – NLU 93
 A short and concise way to construct new sequences (such as
lists, sets, dictionaries, etc.) using previously defined
sequences.

 4 types of comprehension:
◦ List Comprehensions

◦ Dictionary Comprehensions

◦ Set Comprehensions

◦ Generator Comprehensions

Py – NLU 94
 Provide an elegant way to create new lists

 Syntax: [expression for value in iterable if condition]

 Example:

squares = []
n = 10 n = 10
for k in range(1, n + 1): squares = [k*k for k in range(1, n+1)]
[Link](k * k) print(squares)

print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Py – NLU 95


 create a new dictionary

 Syntax: output_dict = {key:value for (key, value) in iterable if


(key, value satisfy this condition)}

input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {} input_list = [1, 2, 3, 4, 5, 6, 7]
for var in input_list:
if var % 2 != 0: dict_using_comp = {var: var ** 3 for var in
output_dict[var] = var ** 3 input_list if var % 2 != 0}

print("Re:", output_dict) print("Re:", dict_using_comp)

Py – NLU Re: {1: 1, 3: 27, 5: 125, 7: 343} 96


 Set comprehensions: { k k for k in range(1, n+1) }
 Tuple comprehensions: ( k k for k in range(1, n+1) )

 Packing/Unpacking of Sequences
a, b, c, d = range(7, 11)
def f(lst):
return sum(lst), max(lst), min(lst) Unpacking

a=7, b=8, c=9, and d=10


lst = [1, 2, 3]
sum, max, min = f(lst)
print(sum, max,min) formally returning a single object that is the
tuple (sum(lst), max(lst), min(lst))

Py – NLU 97
98
 Stack: A collection based on the principle of adding elements
and retrieving them in the opposite order.
◦ Last-In, First-Out ("LIFO")
◦ Elements are stored in order of insertion.
 We do not think of them as having indexes.
◦ Client can only add/remove/examine
the last element added (the "top"). push pop, peek

 Basic stack operations: top 3


◦ push: Add an element to the top. 2
bottom 1
◦ pop: Remove the top element.
stack
Py – NLU
 Python's list data type can be used as a stack without any
modifications by using two native list methods (well for
performance):

◦ .append(): add an element to the end of the list. The method returns
None.

◦ .pop(): remove the right-most element from the list. The method
returns the removed element.

Py – NLU 100
 Example: stack = [1]

# Push elements onto the list-stack


[Link](2)
Method append() as push operation [Link](3)
print(stack) # [1, 2, 3]

# Pop elements from the list-stack


[Link]() # 3
Method pop() used to remove print(stack) # [1, 2]
the last element [Link]() # 2
print(stack) # [1]
Py – NLU 101
 A list as a stack works well for performance

 Limitations of using a Python list as a stack:

◦ A Python list isn't strictly a stack because of allowing access to items at


different indices of the list.

Py – NLU 102
103
 Queue: Retrieves elements in the order they were added.
◦ First-In, First-Out ("FIFO")
◦ Elements are stored in order of
insertion but don't have indexes.
◦ Client can only add to the end of the
queue, and can only examine/remove
the front of the queue.
front back
remove, peek add
1 2 3

 Basic queue operations: queue


◦ add (enqueue): Add an element to the back.
◦ remove (dequeue): Remove the front element.

Py – NLU
 Python's list data type can be used as a queue without any
modifications by using two native list methods:

◦ .append(): add elements to the end of the collection.

◦ .pop(0): used with an argument of 0, remove the first element from the
collection.

Py – NLU 105
queue = []
# Enqueue items
 Example: [Link](1)
[Link](2)
[Link](3)
print(queue) # [1, 2, 3]
Method append() as add operation
# Dequeue items
[Link](0) # 1
print(queue) # [2, 3]
[Link](0) # 2
Method pop(0) used to remove print(queue) # [3]
the first element [Link](0) # 3
print(queue) # []
Py – NLU 106
 Limitations of using a Python list as a queue:

◦ poor performance because of how Python lists are designed.

 Adding an item to the beginning of a list ➔ Python needs to shift all the
other items ➔ high complexity.

◦ access to items at different indices of the list.

Py – NLU 107
108
 Functional programming is a programming paradigm that
treats computation as evaluating mathematical functions and
avoids changing state and mutable data.

 Three built-in functions that are very useful when used with
lists: filter(), map(), and reduce().

 Map, Filter, and Reduce are paradigms of functional programming

Py – NLU 109
 Syntax: filter(func, iterable)
 filter(): the function to return boolean values (true or false)
and then passes each element in the iterable through the
function, "filtering" away those that are false.
◦ Unlike map(), only one iterable is required.
◦ The func argument is required to return a boolean type. Also, as only
one iterable is required, it's implicit that func must only take one
argument.
◦ filter passes each element in the iterable through func and returns only
the ones that evaluate to true..

Py – NLU 110
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]

def is_A_student(score):
 Examples: return score > 75

over_75 = list(filter(is_A_student, scores))

print(over_75)

dromes = ("demigod", "rewire", "madam", "freer", "anutforajaroftuna", "kiosk")

palindromes = list(filter(lambda word: word == word[::-1], dromes))

print(palindromes)

Py – NLU 111
 Syntax: map(func, *iterables)
◦ calls func(item) for each of the sequence’s items and
returns a list of the return values

◦ In Python 3, map function returns a generator object


➔use list() to get the result as a list

◦ The number of arguments to func must be the number of


iterables listed.

Py – NLU 112
 Example:
def cube(x): return x * x * x

results = list(map(cube, range(1, 11)))


print(results)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

seq = range(8)
def add(x, y): return x+y

print(list(map(add, seq, seq)))


[0, 2, 4, 6, 8, 10, 12, 14]

Py – NLU 113
 reduce applies a function of two arguments cumulatively to
the elements of an iterable, optionally starting with an initial
argument
 Syntax: reduce(func, iterable[, initial])
◦ func requires two arguments, the first of which is the first element in
iterable (if initial is not supplied) and the second element in iterable.
◦ If initial is supplied, then it becomes the first argument to func and
the first element in iterable becomes the second element.
◦ reduce "reduces" iterable into a single value.

Py – NLU 114
from functools import reduce

numbers = [3, 4, 6, 9, 34, 12]


 Example:
def custom_sum(first, second):
return first + second
from functools import reduce
result = reduce(custom_sum, numbers)
numbers = [3, 4, 6, 9, 34, 12]
print(result)
def custom_sum(first, second): 68
return first + second

result = reduce(custom_sum, numbers, 10)


print(result)
78 Py – NLU 115
 The zip() function: creates an iterator that will aggregate
elements from two or more iterables
 Syntax: zip(iterator1, iterator2, iterator3 ...)

numbers = [1, 2, 3] numbers = [1, 2, 3]


letters = ['a', 'b', 'c'] zipped = zip(numbers, numbers[1:])
zipped = zip(numbers, letters) print(list(zipped))
print(list(zipped))

[(1, 'a'), (2, 'b'), (3, 'c')] [(1, 2), (2, 3)]
Py – NLU 116
Passing Arguments of Unequal Length: The missing values will
be replaced with whatever you pass to the fillvalue argument
(defaults to None).
numbers = [3, 4, 6, 9, 34, 12]
chars = ['a', 'b','c']
from itertools import zip_longest
zipped = zip(numbers, chars)
print(list(zipped))
numbers = [3, 4, 6, 9, 34, 12]
chars = ['a', 'b','c']
zipped = zip_longest(numbers, chars, fillvalue='?')
print(list(zipped))
[(3, 'a'), (4, 'b'), (6, 'c')]

[(3, 'a'), (4, 'b'), (6, 'c'), (9, '?'), (34, '?'), (12, '?')] Py – NLU 117
 The enumerate() function adds a counter to an iterable and
returns it as an enumerate object (iterator with index and the
value).
 Syntax: enumerate(iterable, start=0)

03
numbers = [3, 4, 6, 9, 34, 12] 14
for count, value in enumerate(numbers): 26
print(count, value) 39
4 34
5 12

Py – NLU 118
FACULTY OF INFORMATION TECHNOLOGY

You might also like