0% found this document useful (0 votes)
13 views

Python Notes of Unit-3

Uploaded by

Varsha Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Notes of Unit-3

Uploaded by

Varsha Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Tuples in Python

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.

Creating Python Tuples

There are various ways by which you can create a tuple in Python. They are as follows:

 Using round brackets

 With one item

 Tuple Constructor

Create Tuples using Round Brackets ()

To create a tuple we will use () operators.

 Python3

var = ("Geeks", "for", "Geeks")

print(var)

Output:

('Geeks', 'for', 'Geeks')

Create a Tuple With One Item

Python 3.11 provides us with another way to create a Tuple.

 Python3

values : tuple[int | str, ...] = (1,2,4,"Geek")

print(values)

Hangup (SIGHUP)

Traceback (most recent call last):

File "Solution.py", line 1, in <module>

values : tuple[int | str, ...] = (1,2,4,"Geek")

TypeError: unsupported operand type(s) for |: 'type' and 'type

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'>

Tuple Constructor in Python

To create a tuple with a Tuple constructor, we will pass the elements as its parameters.

 Python3

tuple_constructor = tuple(("dsa", "developement", "deep learning"))

print(tuple_constructor)

Output :

('dsa', 'developement', 'deep learning')

What is Immutable in Tuples?

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.

 One cannot add items to a tuple once it is created.

 Tuples cannot be appended or extended.

 We cannot remove items from a tuple once it is created.

Let us see this with an example.

 Python3

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

# tuples are indexed

print(mytuple[1])

print(mytuple[4])

# tuples contain duplicate elements

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)

Traceback (most recent call last):

File "e0eaddff843a8695575daec34506f126.py", line 11, in

tuple1[1] = 100

TypeError: 'tuple' object does not support item assignment

Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.

 Using a positive index

 Using a negative index

Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

 Python3

3
var = ("Geeks", "for", "Geeks")

print("Value in Var[0] = ", var[0])

print("Value in Var[1] = ", var[1])

print("Value in Var[2] = ", var[2])

Output:

Value in Var[0] = Geeks

Value in Var[1] = for

Value in Var[2] = Geeks

Access Tuple using Negative Index

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)

print("Value in Var[-1] = ", var[-1])

print("Value in Var[-2] = ", var[-2])

print("Value in Var[-3] = ", var[-3])

Output:

Value in Var[-1] = 3

Value in Var[-2] = 2

Value in Var[-3] = 1

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

 Concatenation

 Nesting

 Repetition

 Slicing

 Deleting

4
 Finding the length

 Multiple Data Types with tuples

 Conversion of lists to tuples

 Tuples in a Loop

Concatenation of Python Tuples

To Concatenation of Python Tuples, we will use plus operators(+).

 Python3

# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'geek')

# Concatenating above two

print(tuple1 + tuple2)

Output:

(0, 1, 2, 3, 'python', 'geek')

Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.

 Python3

# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)

tuple2 = ('python', 'geek')

tuple3 = (tuple1, tuple2)

print(tuple3)

Output :

((0, 1, 2, 3), ('python', 'geek'))

Repetition Python Tuples

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:

('python', 'python', 'python')

Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.

Slicing Tuples in Python

Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.

 Python3

# code to test slicing

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)

Note: In Python slicing, the end index provided is not included.

Deleting a Tuple in Python

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:

Traceback (most recent call last):

File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>

print(tuple3)

NameError: name 'tuple3' is not defined

Finding the Length of a Python Tuple

To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.

 Python3

# Code for printing the length of a tuple

tuple2 = ('python', 'geek')

print(len(tuple2))

Output:

Multiple Data Types With Tuple

Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.

 Python3

# tuple with different datatypes

tuple_obj = ("immutable",True,23)

print(tuple_obj)

Output :

('immutable', True, 23)

Converting a List to a Tuple

7
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its
parameters.

 Python3

# Code for converting a list and a string into a tuple

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)

('p', 'y', 't', 'h', 'o', 'n')

Tuples in a Loop

We can also create a tuple with a single element in it using loops.

 Python3

# python code for creating tuples in a loop

tup = ('geek',)

# Number of time loop runs

n=5

for i in range(int(n)):

tup = (tup,)

print(tup)

Output:

(('geek',),)

((('geek',),),)

(((('geek',),),),)

8
((((('geek',),),),),)

(((((('geek',),),),),),)

Create a List of Tuples in Python

Last Updated : 16 Oct, 2024

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:

Manually creating a list of tuples

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

# Creating a list of tuples manually

a = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]

print(a)

Output

[(1, 'apple'), (2, 'banana'), (3, 'cherry')]

Explanation: We manually create a list called a, which contains three tuples. Each tuple stores a
number paired with a fruit name.

Let’s explore other different methods to create a list of tuples.

Table of Content

 Using a Loop

 Using List Comprehension

 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]

b = ['apple', 'orange', 'cherry']

# Initialize an empty list

res = []

# Using a loop to create tuples and add them to the list

for i in range(len(a)):

res.append((a[i], b[i]))

print(res)

Output

[(1, 'apple'), (2, 'orange'), (3, 'cherry')]

Explanation

 for loop iterates over the indices of the list ‘a‘.

 A tuple is created from each element of list ‘a‘ and list ‘b‘ and appended to res.

Using List Comprehension

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

# Creating a list of tuples using list comprehension

a = [(x, x ** 2) for x in range(5)]

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

Example 2: We have list of list and we want to create list of tuple.

Python

a = [[1, 'apple'], [2, 'orange'], [3, 'cherry']]

# List comprehension to create a list of tuples

a = [tuple(x) for x in a]

10
print(a)

Output

[(1, 'apple'), (2, 'orange'), (3, 'cherry')]

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

# Two lists with ids and name

a = [1, 2, 3]

b = ['apple', 'orange', 'cherry']

# Zip the lists and convert back into a list

a = list(zip(a, b))

print(a)

Output

[(1, 'apple'), (2, 'orange'), (3, 'cherry')]

Explanation:

 zip(a, b): The zip() function pairs elements from a and b together. Here, (1, ‘apple’), (2,
‘orange’), etc., are formed.

 list(zip(a, b)): convert the zip object into a list.

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

a = [[1, 'apple'], [2, 'orange'], [3,'cherry']]

# Using map to convert each list to a tuple

b = list(map(tuple, a))

print(b)

Output

11
[(1, 'apple'), (2, 'orange'), (3, 'cherry')]

Explanation:

 map(tuple, data_lists): Converts each list in ‘a’ into a tuple.

 list(map(…)): Collects the converted tuples into a list. Python – Clearing a tuple

 Last Updated : 18 May, 2023

 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.

 Method #1 : Using list() + clear() + tuple()


The combination of above 3 functions can be used to perform this task. In this, we
interconvert the tuple to list, clear it and again convert to tuple using tuple().

 Python3

 # Python3 code to demonstrate

 # Clearing a tuple

 # using list() + tuple() + clear()

 # initializing tuple

 test_tup = (1, 5, 3, 6, 8)

 # printing original tuple

 print("The original tuple : " + str(test_tup))

 # Clearing a tuple

 # using list() + tuple() + clear()

 temp = list(test_tup)

 temp.clear()

 test_tup = tuple(temp)

12
 # print result

 print("The tuple after clearing values : " + str(test_tup))

 Output :

 The original tuple : (1, 5, 3, 6, 8)

 The tuple after clearing values : ()

 Method #2 : Reinitialization using tuple()


Another straight forward way to perform this task is to reinitialize tuple using tuple() which
will return empty tuple.

 Python3

 # Python3 code to demonstrate

 # Clearing a tuple

 # using Reinitialization + tuple()

 # initializing tuple

 test_tup = (1, 5, 3, 6, 8)

 # printing original tuple

 print("The original tuple : " + str(test_tup))

 # Clearing a tuple

 # using Reinitialization + tuple()

 test_tup = tuple()

 # print result

 print("The tuple after clearing values : " + str(test_tup))

 Output :

 The original tuple : (1, 5, 3, 6, 8)

 The tuple after clearing values : ()

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)

 # printing original tuple

 print("The original tuple : " + str(test_tup))

 # Clearing a tuple using * operator

 test_tup = test_tup * 0

 # print result

 print("The tuple after clearing values : " + str(test_tup))

 #This code is contributed by Edula Vinay Kumar Reddy

 Output

 The original tuple : (1, 5, 3, 6, 8)

 The tuple after clearing values : ()

 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.

 Method #4: Using slicing and concatenation

 Initialize a tuple called test_tup with values (1, 5, 3, 6, 8).

 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)

 # printing original tuple

 print("The original tuple : " + str(test_tup))

 # Clearing a tuple using slicing and concatenation

 test_tup = test_tup[0:0] + ()

 # print result

 print("The tuple after clearing values : " + str(test_tup))

 Output

 The original tuple : (1, 5, 3, 6, 8)

 The tuple after clearing values : ()

 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.

 METHOD 5:Using the del keyword

 APPROACH:

 In this approach, we can simply delete the original tuple using the del keyword, which clears
all the values of the tuple.

 ALGORITHM:

 1. Assign the tuple to a variable.


2. Use the del keyword to delete the tuple.
3. Print the original tuple and an empty tuple to show that all values have been cleared.

 Python3

 # Input

 tup = (1, 5, 3, 6, 8)

 # Delete the original tuple using the del keyword

 del tup

15

 # Output

 print("The original tuple:", (1, 5, 3, 6, 8))

 print("The tuple after clearing values:", ())

 Output

 The original tuple: (1, 5, 3, 6, 8)

 The tuple after clearing values: ()

 Time Complexity: O(1)


Space Complexity: O(1)

Convert list to tuple in Python

Last Updated : 11 Oct, 2024

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]

# Convert the list into a tuple

t = tuple(a)

print('tuple:', t)

Output

a: [1, 2, 3, 4, 5]

t: (1, 2, 3, 4, 5)

Why convert a list to a tuple?

Let’s see, why we might want to convert a list to a tuple:

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

 Using tuple() Function

 Using the Unpacking Operator *

 Using a Generator Expression

 Convert an Empty List into a Tuple

 Convert a Nested List into a Tuple

Now, Lets see the other different ways to convert list to tuple

Using loop inside the 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]

# Convert the list into a tuple using a generator expression

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.

Using the unpacking operator *

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.

Convert a nested list into a tuple

We can also convert a list containing nested lists into a tuple.

Python

# A nested list

a = [[1, 2], [3, 4], [5, 6]]

# Convert the nested list into a tuple

t = tuple(a)

print(t)

Output

([1, 2], [3, 4], [5, 6])

Explanation: The tuple function does not change the data types of the nested objects.

Convert a list into a tuple – FAQs

1. How do I convert a list to a tuple in Python?

To convert a list to a tuple in Python, you can use the tuple() function. For example:

a = [1, 2, 3]
a = tuple(a)

2. Why should I convert a list to a tuple?

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.

3. What is the difference between a list and a tuple?

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.

Python 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

index() Searches the tuple for a specified value and returns the position of where it was found

Python Tuple count() Method

Example

Return the number of times the value 5 appears in the tuple:

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.count(5)

print(x)

Definition and Usage

The count() method returns the number of times a specified value appears in the tuple.

Syntax

tuple.count(value)

Parameter Values

Parameter Description

value Required. The item to search for

19
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

Dictionary Items

Dictionary items are ordered, changeable, and do not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.

Example

Print the "brand" value of the dictionary:

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.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

20
Example

Duplicate values will overwrite existing values:

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 the number of items in the dictionary:

print(len(thisdict))

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

Example

String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary.

Example

Using the dict() method to make a dictionary:

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

Example

Get the value of the "model" key:

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

Get the value of the "model" key:

x = thisdict.get("model")

Get Values

The values() method will return a list of all the values in the dictionary.

Example

Get a list of the values:

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()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

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

Get a list of the key:value pairs

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()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

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()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

23
Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:

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

Change the "year" to 2018:

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.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example

Update the "year" of the car by using the update() method:

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:

ExampleGet your own Python Server

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.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example

Add a color item to the dictionary by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

Removing Items

There are several methods to remove items from a dictionary:

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)

The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

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

Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

Print all values in the dictionary, one by one:

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

A dictionary can contain dictionaries, this is called nested dictionaries.

ExampleGet your own Python Server

Create a dictionary that contain three 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)

Access Items in Nested Dictionaries

To access items from a nested dictionary, you use the name of the dictionaries, starting with
the outer dictionary:

Example

Print the name of child 2:

print(myfamily["child2"]["name"])

Loop Through Nested Dictionaries

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

for x, obj in myfamily.items():

print(x)

for y in obj:

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

Dictionary Methods

Python has a set of built-in methods that you can use 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

28
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, w

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

Python Functions

❮ PreviousNext ❯

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.

Creating a Function

In Python a function is defined using the def keyword:

ExampleGet your own Python Server

def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function():
print("Hello from a function")

my_function()

Try it Yourself »

29
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.

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

You might also like