Unit III: Data Structures in Python
Lists - Operations, Slicing, Methods; Tuples: Creating, Printing, properties of
tuples, Sets, Dictionaries, Sequences and their properties. Defining Functions,
Calling Functions, Passing Arguments, Keyword Arguments, (Function Returning
Values), Scope of the Variables in a Function - Global and Local Variables
What is a List?
In other programming languages, list objects are declared similarly to arrays. Lists don't
have to be homogeneous all the time, so they can simultaneously store items of
different data types. Lists are helpful when we need to iterate over some elements and
keep hold of the items.
What is a Tuple?
A tuple is another data structure to store the collection of items of many data types, but
unlike mutable lists, tuples are immutable. Because of its static structure, the tuple is
more efficient than the list.
Differences between Lists and Tuples
List and Tuple Syntax Differences
The syntax of a list differs from that of a
tuple. Items of a tuple are enclosed by
parentheses or curved brackets (),
whereas items of a list are enclosed
by square brackets [].
Mutable List vs. Immutable Tuple
An important difference between a list and a tuple is that lists are mutable, whereas tuples are
immutable. It means a list's items can be changed or modified, whereas a tuple's items
cannot be changed or modified.
Python Slicing
Both lists and tuples allow you to extract a subset of elements using slicing
Tuples are Memory Efficient
As tuples are stored in a single memory block therefore they don’t require extra space for
new objects whereas the lists are allocated in two blocks, first the fixed one with all
the Python object information and second a variable-sized block for the data.
Python Indexing
Both lists and tuples allow you to access individual elements using their index, starting
from 0.
Python Slicing
Both lists and tuples allow you to
extract a subset of elements using
slicing.
Python Concatenation
Both lists and tuples can be concatenated
using the “+” operator.
Python Append
Lists can be appended with new elements
using the append() method.
Python Extend
Lists can also be extended with another list
using the extend() method.
Python Remove
Lists can have elements removed using the
remove() method.
Differences between List and Tuple in Python
Sno LIST TUPLE
1 Lists are mutable Tuples are immutable
The implication of iterations is Time- The implication of iterations is
2
consuming comparatively Faster
The list is better for performing
A Tuple data type is appropriate for
3 operations, such as insertion and
accessing the elements
deletion.
Tuple consumes less memory as
4 Lists consume more memory
compared to the list
Tuple does not have many built-in
5 Lists have several built-in methods
methods.
Unexpected changes and errors are
6 In a tuple, it is hard to take place.
more likely to occur
Tuples and Lists: Key Similarities
• They both hold collections of items and are heterogeneous data types, meaning they
can contain multiple data types simultaneously.
• They're both ordered, which implies the items or objects are maintained in the same
order as they were placed until changed manually.
• Because they're both sequential data structures, we can iterate through the objects
they hold; hence, they are iterables.
• An integer index, enclosed in square brackets [index], can be used to access objects of
both data types.
When to Use Tuples Over Lists?
In Python, tuples and lists are both used to store collections of data, but they have some
important differences. Here are some situations where you might want to use tuples instead of
lists –
Immutable Data – Tuples are immutable, thus once they are generated, their contents
cannot be changed. This makes tuples a suitable option for storing information that
shouldn’t change, such as setup settings, constant values, or other information that
should stay the same while your program is running.
Performance – Tuples are more lightweight than lists and might be quicker to generate,
access, and iterate through since they are immutable. Using a tuple can be more effective
than using a list if you have a huge collection of data that you need to store, retrieve, and
use regularly and that data does not need to be altered.
Data integrity – By ensuring that the data’s structure and contents stay consistent,
tuples can be utilized to ensure data integrity. To make sure the caller is aware of how
much data to expect, for instance, if a function returns a set amount of values, you might
want to return them as a tuple rather than a list.
Python - Access List Items
1. Access Items
List items are indexed and you
can access them by referring to
the index number.
2. Negative Indexing
Negative indexing means start
from the end
-1 refers to the last item, -2
refers to the second last item
etc.
3. Range of Indexes
You can specify a range of
indexes by specifying where to
start and where to end the
range.
When specifying a range, the
return value will be a new list
with the specified items.
Python - Change List Items
1. Change Item Value
To change the value of a specific
item, refer to the index number.
2. Change a Range of Item
Values
To change the value of items within
a specific range, define a list with
the new values, and refer to the
range of index numbers where you
want to insert the new values.
3. Insert Items
To insert a new list item, without
replacing any of the existing
values, we can use the insert()
method. The insert() method
inserts an item at the specified
index.
Python - Add List Items
1. Append Items
To add an item to the end of the list,
use the append() method.
2. Insert Items
To insert a list item at a specified
index, use the insert() method.
The insert() method inserts an item
at the specified index.
3. Extend List
To append elements from another list
to the current list, use the extend()
method.
4. Add Any Iterable
The extend() method does not have to
append lists, you can add any
iterable object (tuples, sets,
dictionaries etc.).
Python - Remove List Items
1. Remove Specified Item
The remove() method removes
the specified item.
2. Remove Specified Index
The pop() method removes the
specified index.
3. Clear the List
The clear() method empties the
list.
The list still remains, but it has
no content.
Python - List Comprehension
List Comprehension
List comprehension offers a shorter
syntax when you want to create a
new list based on the values of an
existing list.
Example:
Based on a list of fruits, you want a
new list, containing only the fruits
with the letter "a" in the name.
Without list comprehension you will
have to write a for statement with a
conditional test inside:
Python - Loop Lists
1. Loop Through a List
You can loop through the list items by
using a for loop
2. Loop Through the Index Numbers
You can also loop through the list items
by referring to their index number.
Use the range() and len() functions to
create a suitable iterable.
3. Using a While Loop
You can loop through the list items by
using a while loop. Use the len()
function to determine the length of the
list, then start at 0 and loop your way
through the list items by referring to
their indexes.
Remember to increase the index by 1
after each iteration.
4. Looping Using List Comprehension
List Comprehension offers the shortest
syntax for looping through lists
Python - Join Lists
Join Two Lists
There are several ways to
join, or concatenate, two or
more lists in Python.
1. One of the easiest ways
are by using the +
operator.
2. Another way to join two
lists is by appending all
the items from list2 into
list1, one by one.
3. Or you can use the
extend() method, where
the purpose is to add
elements from one list to
another list
Copy a List
You cannot copy a list simply by typing list2 =
list1, because: list2 will only be a reference to
list1, and changes made in list1 will
automatically also be made in list2.
There are ways to make a copy, one way is to
use the built-in List method copy().
Python - Sort Lists
1. Sort List Alphanumerically
List objects have a sort() method
that will sort the list
alphanumerically, ascending, by
default.
2. Sort Descending
To sort descending, use the
keyword argument reverse =
True.
3. Customize Sort Function
Using the keyword argument key
= function.
The function will return a
number that will be used to sort
the list (the lowest number first).
4. Case Insensitive Sort
By default the sort() method is case
sensitive, resulting in all capital
letters being sorted before lower
case letters.
5. Reverse Order
The reverse() method reverses the
current sorting order of the
elements.
Python List count() Method
The count() method returns
the number of elements with
the specified value.
Python List index() Method
The index() method returns the
position at the first occurrence of
the specified value.
Python Tuples Unchangeable
mytuple = ("apple", "banana", "cherry") Tuples are unchangeable, meaning that we
cannot change, add or remove items after the
Tuple tuple has been created.
Tuples are used to store multiple items in a Allow Duplicates
single variable. Since tuples are indexed, they can have items
A tuple is a collection which is ordered and with the same value:
unchangeable. Tuple Length
Tuples are written with round brackets. To determine how many items a tuple has, use
the len() function:
1. Create a Tuple
Tuple items are ordered, unchangeable, and Create Tuple With One Item
allow duplicate values. To create a tuple with only one item, you have
to add a comma after the item, otherwise
Tuple items are indexed, the first item has Python will not recognize it as a tuple.
index [0], the second item has index [1] etc.
Ordered #NOT a tuple
When we say that tuples are ordered, it thistuple = ("apple")
means that the items have a defined order, print(type(thistuple))
and that order will not change.
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")
The tuple() Constructor
It is also possible to use the tuple()
constructor to make a tuple.
Python - Update Tuples
Accessing tuples is same as that of
lists
1. Change Tuple Values
Once a tuple is created, you cannot
change its values. Tuples are
unchangeable, or immutable as it also is
called.
2. Add Items
Since tuples are immutable, they do not
have a built-in append() method, but
there are other ways to add items to a
tuple.
1. Convert into a list: you can convert it
into a list, add your item(s), and
convert it back into a tuple.
2. Add tuple to a tuple: if you want to
add one item, (or many), create a new
tuple with the item(s), and add it to
the existing tuple:
3. Remove Items
Tuples are unchangeable, so you
cannot remove items from it, but you
can use the same workaround as we
used for changing and adding tuple
items:
Python - Unpack Tuples
1. Unpacking a Tuple
When we create a tuple, we normally
assign values to it. This is called
"packing" a tuple.
But, in Python, we are also allowed to
extract the values back into variables.
This is called "unpacking“.
2. Using Asterisk*
The number of variables must match
the number of values in the tuple, if not,
you must add an * to the variable name
and the values will be assigned to the
variable as a list.
If the asterisk is added to another
variable name than the last, Python will
assign values to the variable until the
number of values left matches the
number of variables left.
Python - Loop Tuples
1. Loop Through a Tuple
You can loop through the tuple
items by using a for loop.
2. Loop Through the Index
Numbers
You can also loop through the
tuple items by referring to their
index number.
Use the range() and len()
functions to create a suitable
iterable.
3. Using a While Loop
You can loop through the tuple
items by using a while loop.
Remember to increase the index
by 1 after each iteration.
Python - Join Tuples
1. Join Two Tuples
To join two or more tuples you
can use the + operator.
2. Multiply Tuples
If you want to multiply the
content of a tuple a given number
of times, you can use the *
operator.
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
Searches the tuple for a specified value and returns the position of where it was
index()
found
Python Sets
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Tuple, and Dictionary.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• * Note: Set items are unchangeable, but you can remove items and add new items.
• Note: Sets are unordered, so you cannot be sure in which order the items will appear.
• Set Items
• Set items are unordered, unchangeable, and do not allow duplicate values.
• There are four collection data types in the Python programming language:
❖ List is a collection which is ordered and changeable. Allows duplicate members.
❖ Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
❖ Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
❖ Dictionary is a collection which is ordered** and changeable. No duplicate members.
• *Set items are unchangeable, but you can remove items and add new items.
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.
Syntax:
thisset = {"apple", "banana", "cherry"}
print(thisset)
1. Duplicates Not Allowed
Sets cannot have two items with the
same value. The values True and 1 are
considered the same value in sets, and
are treated as duplicates.
2. Get the Length of a Set
To determine how many items a set
has, use the len() function.
3. Set Items - Data Types
Set items can be of any data type
4. type()
From Python's perspective, sets are
defined as objects with the data type
'set’
5. The set() Constructor
It is also possible to use the set()
constructor to make a set.
Python - Access Set Items
1. Access Items
You cannot access items in a set by referring to
an index or a key. But you can loop through
the set items using a for loop, or ask if a
specified value is present in a set, by using the
in keyword.
Python - Add Set Items
1. Add Items
To add one item to a set use the add() method.
2. Add Sets
To add items from another set into the current
set, use the update() method.
3. Add Any Iterable
The object in the update() method does not
have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Python - Remove Set Items
Remove Item
To remove an item in a set, use the
remove(), or the discard() method.
Remove a random item by using the
pop() method.
The clear() method empties the set.
The del keyword will delete the set
completely.
Python - Loop Sets
Loop Items
You can loop through the set items by using a for loop:
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Python - Join Sets
1. Join Two Sets
There are several ways to join two or
more sets in Python.
You can use the union() method that
returns a new set containing all
items from both sets, or the update()
method that inserts all the items
from one set into another:
Both union() and update() will
exclude any duplicate items.
2. Keep ONLY the Duplicates
The intersection_update() method will
keep only the items that are present
in both sets.
The intersection() method will return
a new set, that only contains the
items that are present in both sets.
3. Keep All, But NOT the
Duplicates
The symmetric_difference_update()
method will keep only the
elements that are NOT present in
both sets.
The symmetric_difference()
method will return a new set, that
contains only the elements that
are NOT present in both sets.
The values True and 1 are
considered the same value in sets,
and are treated as duplicates.
3. Python Set issubset() Method
Python - Set Methods
Example
1. Python Set copy() Method
Return True if all items in set x are present in
Example set y:
Copy the fruits set: x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
fruits = {"apple", "banana", "cherry"} z = [Link](y)
x = [Link]() print(z)
print(x)
4. Python Set issuperset() Method
2. Python Set isdisjoint() Method
Example
Example
Return True if no items in set x is
Return True if all items set y are present in set
present in set y:
x:
x = {"f", "e", "d", "c", "b", "a"}
x = {"apple", "banana", "cherry"}
y = {"a", "b", "c"}
y = {"google", "microsoft", "facebook"}
z = [Link](y)
z = [Link](y)
print(z)
print(z)
Python Dictionaries
thisdict = { Ordered or Unordered?
"brand": "Ford",
"model": "Mustang", As of Python version 3.7, dictionaries are
"year": 1964 ordered. In Python 3.6 and earlier, dictionaries
} are unordered.
Dictionary
Changeable
Dictionaries are used to store data values
in key:value pairs. Dictionaries are changeable, meaning that we
can change, add or remove items after the
A dictionary is a collection which is dictionary has been created.
ordered*, changeable and do not allow
duplicates. Duplicates Not Allowed
As of Python version 3.7, dictionaries are Dictionaries cannot have two items with the
ordered. In Python 3.6 and earlier, same key.
dictionaries are unordered.
Dictionaries are written with curly
brackets, and have keys and values:
Dictionary Length
type()
From Python's perspective, dictionaries are
To determine how many items a
defined as objects with the data type 'dict':
dictionary has, use the len() function.
<class 'dict'>
Example
Example
Print the number of items in the
Print the data type of a dictionary:
dictionary:
thisdict = {
print(len(thisdict))
"brand": "Ford",
"model": "Mustang",
"year": 1964
Dictionary Items - Data Types
print(type(thisdict))
The values in dictionary items can be of
any data type:
The dict() Constructor
Example
It is also possible to use the dict() constructor
String, int, boolean, and list data types:
to make a dictionary.
thisdict = {
Example
"brand": "Ford",
Using the dict() method to make a dictionary:
"electric": False,
thisdict = dict(name = "John", age = 36,
"year": 1964,
country = "Norway")
"colors": ["red", "white", "blue"]
print(thisdict)
}
Python - Access Dictionary Items
Accessing Items
You can access the items of a dictionary by
referring to its key name, inside square
brackets.
Get Keys
The keys() method will return a list of all the
keys in the dictionary.
Get Values
The values() method will return a list of all
the values in the dictionary.
The list of the values is a view of the
dictionary, meaning that any changes done
to the dictionary will be reflected in the
values list.
Get Items
The items() method will return
each item in a dictionary, as
tuples in a list.
Check if Key Exists
To determine if a specified key is
present in a dictionary use the
in keyword
Python - Change Dictionary Items
You can change the value of a specific item by
referring to its key name.
Python - Add Dictionary Items
Adding an item to the dictionary is done
by using a new index key and assigning a
value to it.
Update Dictionary
The update() method will update the
dictionary with the items from a given
argument. If the item does not exist, the
item will be added.
The argument must be a dictionary, or an
iterable object with key:value pairs.
Python - Remove Dictionary
Items
popitem() method removes the
last inserted item (in versions
before 3.7, a random item is
removed instead)
Python - Loop Dictionaries
You can loop through a
dictionary by using a for
loop.
Python - Copy Dictionaries
Copy a Dictionary
Python - Nested Dictionaries
Nested Dictionaries
A dictionary can contain dictionaries,
this is called nested dictionaries.
Access Items in Nested
Dictionaries
To access items from a nested
dictionary, you use the name of the
dictionaries, starting with the outer
dictionary.
Python Functions
A function is a block of code which only
runs when it is called. You can pass data,
known as parameters, into a function. A
function can return data as a result.
1. Creating a Function
In Python a function is defined using the
def keyword.
2. Calling a Function
To call a function, use the function name
followed by parenthesis.
3. Arguments
Information can be passed into functions
as arguments. Arguments are specified
after the function name, inside the
parentheses. You can add as many
arguments as you want, just separate them
with a comma.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called
with the correct number of arguments.
Meaning that if your function expects 2
arguments, you have to call the
function with 2 arguments, not more,
and not less.
Arbitrary Arguments, *args
If you do not know how many
arguments that will be passed into your
function, add a * before the parameter
name in the function definition.
This way the function will receive a
tuple of arguments, and can access the
items accordingly.
Keyword Arguments
You can also send arguments with the
key = value syntax.
This way the order of the arguments
does not matter.
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function,
add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly.
If the number of keyword arguments is unknown, add a double ** before the parameter
name.
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value.
Passing a List as an Argument
You can send any data types of argument to a
function (string, number, list, dictionary etc.),
and it will be treated as the same data type
inside the function.
E.g. if you send a List as an argument, it will
still be a List when it reaches the function.
Return Values
To let a function return a value, use the return
statement.
Call by value and Call by reference
Global and Local Variables