Python Sequence Types and Containers
Python Sequence Types and Containers
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 : [ ]
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:
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
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
no
index key yes no yes no yes no
access
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
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()
# 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)
# 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]
Py – NLU 24
Loop through the list items using for loop
Loop through the list items by referring to their index number
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
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"]
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:
Py – NLU 29
Syntax: [Link](reverse, key)
Parameters:
◦ reverse - By default False. If True is passed, the list is sorted in
descending order.
Py – NLU 30
List objects have a sort() method that will sort the list
alphanumerically, ascending (default)
◦ in-place sort
[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
[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
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)
Py – NLU 38
Use the list() method
lst = ["apple", "banana", "cherry"]
lst1 = list(lst) Deep or
lst1[0] = "APPLE" Shallow
copy?
print(lst)
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)
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)
s = 'Python'
list(reversed(range(len(s))))
Py – NLU 47
48
A collection of unique elements
x = {<obj>, <obj>, ..., <obj>}
* 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
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
Py – NLU 52
Cannot access items in a set by referring to an index or a key:
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
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
[Link](set2)
Py – NLU 56
Keep ONLY the duplicates
Syntax:
[Link](x2[, x3 ...])
Py – NLU 57
Using intersection() or & to the set of elements common to
both sets
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.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
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.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
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.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.
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)
Py – NLU 71
Using + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple4 = tuple1 * 2
print(tuple4)
Py – NLU 72
Using sort() method?
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:
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.
Py – NLU 78
Accessing item: x = d[“ca"]
Py – NLU 79
Change Values: my_dict["year"] = 2018
Py – NLU 80
Remove an item: my_dict.pop("model")
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
Py – NLU 83
Using = operator
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
copy_dict = my_dict
copy_dict["year"] = 2024
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
copy_dict = my_dict.copy()
copy_dict["year"] = 2024
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
copy_dict = dict(my_dict)
copy_dict["year"] = 2024
dh22dtc
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 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)
4 types of comprehension:
◦ List Comprehensions
◦ Dictionary Comprehensions
◦ Set Comprehensions
◦ Generator Comprehensions
Py – NLU 94
Provide an elegant way to create new lists
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)
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}
Packing/Unpacking of Sequences
a, b, c, d = range(7, 11)
def f(lst):
return sum(lst), max(lst), min(lst) Unpacking
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
◦ .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]
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
Py – NLU
Python's list data type can be used as a queue without any
modifications by using two native list methods:
◦ .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:
Adding an item to the beginning of a list ➔ Python needs to shift all the
other items ➔ high complexity.
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().
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
print(over_75)
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
Py – NLU 112
Example:
def cube(x): return x * x * x
seq = range(8)
def add(x, y): return x+y
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
[(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