Python Notes of Unit-3
Python Notes of Unit-3
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a
Python list in terms of indexing, nested objects, and repetition but the main difference between both
is Python tuple is immutable, unlike the Python list which is mutable.
There are various ways by which you can create a tuple in Python. They are as follows:
Tuple Constructor
Python3
print(var)
Output:
Python3
print(values)
Hangup (SIGHUP)
Output:
Here, in the above snippet we are considering a variable called values which holds a tuple that
consists of either int or str, the ‘…’ means that the tuple will hold more than one int or str.
(1, 2, 4, 'Geek')
1
Note: In case your generating a tuple with a single element, make sure to add a comma after the
element. Let us see an example of the same.
Python3
mytuple = ("Geeks",)
print(type(mytuple))
#NOT a tuple
mytuple = ("Geeks")
print(type(mytuple))
Output:
<class 'tuple'>
<class 'str'>
To create a tuple with a Tuple constructor, we will pass the elements as its parameters.
Python3
print(tuple_constructor)
Output :
Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered and
allow duplicate values. Some Characteristics of Tuples in Python.
We can find items in a tuple since finding any item does not make changes in the tuple.
Python3
2
mytuple = (1, 2, 3, 4, 5)
print(mytuple[1])
print(mytuple[4])
mytuple = (1, 2, 3, 4, 2, 3)
print(mytuple)
# adding an element
mytuple[1] = 100
print(mytuple)
Output:
Python tuples are ordered and we can access their elements using their index values. They are also
immutable, i.e., we cannot add, remove and change the elements once declared in the tuple, so
when we tried to add an element at index 1, it generated the error.
(1, 2, 3, 4, 2, 3)
tuple1[1] = 100
Tuples in Python provide two ways by which we can access the elements of a tuple.
Using square brackets we can get the values from tuples in Python.
Python3
3
var = ("Geeks", "for", "Geeks")
Output:
In the above methods, we use the positive index to access the value in Python, and here we will use
the negative index within [].
Python3
var = (1, 2, 3)
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
Concatenation
Nesting
Repetition
Slicing
Deleting
4
Finding the length
Tuples in a Loop
Python3
tuple1 = (0, 1, 2, 3)
print(tuple1 + tuple2)
Output:
Python3
tuple1 = (0, 1, 2, 3)
print(tuple3)
Output :
We can create a tuple of multiple same elements from a single element in that tuple.
Python3
5
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
Output:
Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.
Python3
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Output:
In this example, we sliced the tuple from index 1 to the last element. In the second print statement,
we printed the tuple using reverse indexing. And in the third print statement, we printed the
elements from index 2 to 4.
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error
because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del
keyword.
Python3
6
# Code for deleting a tuple
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Output:
print(tuple3)
To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.
Python3
print(len(tuple2))
Output:
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.
Python3
tuple_obj = ("immutable",True,23)
print(tuple_obj)
Output :
7
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its
parameters.
Python3
list1 = [0, 1, 2]
print(tuple(list1))
# string 'python'
print(tuple('python'))
Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are
taken as elements), and converts them to a tuple.
(0, 1, 2)
Tuples in a Loop
Python3
tup = ('geek',)
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)
Output:
(('geek',),)
((('geek',),),)
(((('geek',),),),)
8
((((('geek',),),),),)
(((((('geek',),),),),),)
List of tuple is used to store multiple tuples together into List. We can create a list that
contains tuples as elements. This practice is useful for memory efficiency and data security as tuples
are immutable. The simplest way to create a list of tuples is to define it manually by specifying the
values. Let’s take an example:
The simplest way to create a list of tuples is to define it manually by specifying each tuple within the
list. This approach is suitable when we have a small set of data.
Python
print(a)
Output
Explanation: We manually create a list called a, which contains three tuples. Each tuple stores a
number paired with a fruit name.
Table of Content
Using a Loop
Using zip()
Using map()
Using a Loop
Using a loop (for loop) is another way to create a list of tuples but this is particularly useful when we
require more complex processing over elements.
Python
9
a = [1, 2, 3]
res = []
for i in range(len(a)):
res.append((a[i], b[i]))
print(res)
Output
Explanation
A tuple is created from each element of list ‘a‘ and list ‘b‘ and appended to res.
We can also use list comprehensions to create a list of tuples. This approach is an alternative of
above loop approach but this approach is very concise and readable.
Example 1: Suppose we want to pair the numbers with their square then lets take a look at below
example about how to do it.
Python
print(a)
Output
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
Explanation: [(x, x + 1) for x in range(5)] generate tuples where each element x is paired with x + 1
Python
a = [tuple(x) for x in a]
10
print(a)
Output
Using zip()
We can create a list of tuples from any number of list using the zip() function. The zip() function
takes multiple lists and create pairs of elements from all the list and returns a zip object, after that
we need to convert this zip object back to list.
Python
a = [1, 2, 3]
a = list(zip(a, b))
print(a)
Output
Explanation:
zip(a, b): The zip() function pairs elements from a and b together. Here, (1, ‘apple’), (2,
‘orange’), etc., are formed.
Using map()
We can use the map() function to convert a list of lists into a list of tuples. We simply need to pass
two argument to map function: tuple() constructor and a list of lists.
Python
b = list(map(tuple, a))
print(b)
Output
11
[(1, 'apple'), (2, 'orange'), (3, 'cherry')]
Explanation:
list(map(…)): Collects the converted tuples into a list. Python – Clearing a tuple
Sometimes, while working with Records data, we can have a problem in which we may
require to perform clearing of data records. Tuples, being immutable cannot be modified and
hence makes this job tough. Let’s discuss certain ways in which this task can be performed.
Python3
# Clearing a tuple
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
# Clearing a tuple
temp = list(test_tup)
temp.clear()
test_tup = tuple(temp)
12
# print result
Output :
Python3
# Clearing a tuple
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
# Clearing a tuple
test_tup = tuple()
# print result
Output :
13
Method #3: Using * operator
This method uses the * operator to create a new tuple with zero copies of the original tuple.
Python3
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
test_tup = test_tup * 0
# print result
Output
All of the above methods for clearing a tuple have a time complexity of O(n) and an auxiliary
space of O(1) because the operations are performed on the existing tuple.
Print the original tuple using the print() function and the string concatenation operation +.
The str() function is used to convert the tuple to a string.
Use slicing and concatenation to clear the tuple. Slicing is used to get an empty tuple, and
concatenation is used to combine it with the original tuple. The resulting tuple is assigned
back to the variable test_tup.
Print the resulting tuple using the print() function and the string concatenation operation +.
The str() function is used to convert the tuple to a string.
Python3
14
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
test_tup = test_tup[0:0] + ()
# print result
Output
Time complexity: O(n) where n is the length of the tuple, because slicing takes O(n) time.
Auxiliary space: O(1), because no extra memory is used.
APPROACH:
In this approach, we can simply delete the original tuple using the del keyword, which clears
all the values of the tuple.
ALGORITHM:
Python3
# Input
tup = (1, 5, 3, 6, 8)
del tup
15
# Output
Output
In Python, data types serve different purposes and converting between them is common.
You might need to convert a list to a tuple to keep data unchanged. The most simple way
to convert a list into a tuple is by using the built-in tuple() function.
Example: Here’s an example to convert a list into a tuple using the tuple() function.
The tuple() constructor takes an iterable (in this case, a list) as its argument and returns a
tuple.
Python
a = [1, 2, 3, 4, 5]
t = tuple(a)
print('tuple:', t)
Output
a: [1, 2, 3, 4, 5]
t: (1, 2, 3, 4, 5)
16
Immutability: Once you convert a list to a tuple, the data becomes immutable. This means it
can’t be changed by mistake.
Data Integrity: If we have data that shouldn’t be modified, tuples are a better choice than
lists.
Performance: Tuples can use less memory and can be quicker to access compared to lists.
Table of Content
Now, Lets see the other different ways to convert list to tuple
This method is a slight variation of the previous approach. We can use a loop inside
the tuple() function to convert a Python list into a tuple. This involves using a generator
expression within the tuple() function.
Python
a = [1, 2, 3, 4, 5]
t = tuple(x for x in a)
print(t)
Output
(1, 2, 3, 4, 5)
Explanation: (x for x in a) iterates over each element x in the list and the tuple() function
takes the generator expression as an argument and converts it into a tuple.
Note: This approach is least commonly used for converting list to tuple, it demonstrates
Python’s flexibility and capabilities for creating complex expressions.
We can convert a list into a tuple using the unpacking operator * inside parentheses ().
Python
a = [1, 2, 3, 4]
17
# Convert the list into a tuple using unpacking
b = (*a, )
print(b)
Output
(1, 2, 3, 4)
Explanation:
The *a (unpacking operator) unpacks the elements of the list a and passes them as separate
arguments inside parentheses ().
The result (*a, ) creates a tuple with the unpacked elements from the list a. The trailing
comma (,) ensures that the result is a tuple.
To get more about ‘*‘ operator, please refer to Packing and Unpacking in Python.
Python
# A nested list
t = tuple(a)
print(t)
Output
Explanation: The tuple function does not change the data types of the nested objects.
To convert a list to a tuple in Python, you can use the tuple() function. For example:
a = [1, 2, 3]
a = tuple(a)
18
You may want to convert a list to a tuple to make the data immutable, to make sure it cannot
be changed accidentally, which is useful for maintaining data integrity.
A list is mutable, meaning its elements can be changed, while a tuple is immutable, meaning
it cannot be modified after creation. This difference makes tuples useful when you need data
to remain constant.
Method Description
index() Searches the tuple for a specified value and returns the position of where it was found
Example
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
The count() method returns the number of times a specified value appears in the tuple.
Syntax
tuple.count(value)
Parameter Values
Parameter Description
19
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionary Items
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an item by
using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
20
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
print(len(thisdict))
Example
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
Example
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
thisdict = {
"brand": "Ford",
21
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Get Values
The values() method will return a list of all the values in the dictionary.
Example
x = thisdict.values()
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.
Example
Make a change in the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["year"] = 2020
Example
Add a new item to the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
22
print(x) #before the change
car["color"] = "red"
print(x)
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
x = thisdict.items()
The returned list is a view of the items of the dictionary, meaning that any changes done to
the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["year"] = 2020
Add a new item to the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["color"] = "red"
23
Check if Key Exists
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Change Values
You can change the value of a specific item by referring to its key name:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
thisdict = {
"brand": "Ford",
24
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
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.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Removing Items
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
The del keyword removes the item with the specified key name:
25
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
When looping through a dictionary, the return value are the keys of the dictionary, but there
are methods to return the values as well.
Example
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])
You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
Nested Dictionaries
26
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
To access items from a nested dictionary, you use the name of the dictionaries, starting with
the outer dictionary:
Example
print(myfamily["child2"]["name"])
You can loop through a dictionary by using the items() method like this:
Example
27
Loop through the keys and values of all nested dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
print(x)
for y in obj:
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
28
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, w
Python Functions
❮ PreviousNext ❯
Creating a Function
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Try it Yourself »
29
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.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
30