0% found this document useful (0 votes)
14 views8 pages

Chapter 10 Tuples and Dictionaries

Chapter 10 covers tuples and dictionaries in Python, detailing the structure and properties of tuples, including their immutability, indexing, and various operations such as concatenation and slicing. It also introduces dictionaries as unordered collections of key-value pairs, explaining how to access, modify, and delete elements, as well as various built-in methods for manipulation. The chapter includes examples and exercises to reinforce understanding of these data structures.

Uploaded by

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

Chapter 10 Tuples and Dictionaries

Chapter 10 covers tuples and dictionaries in Python, detailing the structure and properties of tuples, including their immutability, indexing, and various operations such as concatenation and slicing. It also introduces dictionaries as unordered collections of key-value pairs, explaining how to access, modify, and delete elements, as well as various built-in methods for manipulation. The chapter includes examples and exercises to reinforce understanding of these data structures.

Uploaded by

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

Chapter 10 Tuples and Dictionaries

July 28, 2024

Chapter 10: Tuples and Dictionaries


10.1 Introduction to Tuples A tuple is an ordered sequence of elements of different data
types, such as integer, float, string, list, or even another tuple. Elements of a tuple are enclosed in
parentheses and separated by commas. Like lists and strings, elements of a tuple can be accessed
using index values, starting from 0.
Examples:

[ ]: # tuple1 is the tuple of integers


tuple1 = (1, 2, 3, 4, 5)
print(tuple1) # Output: (1, 2, 3, 4, 5)

# tuple2 is the tuple of mixed data types


tuple2 = ('Economics', 87, 'Accountancy', 89.6)
print(tuple2) # Output: ('Economics', 87, 'Accountancy', 89.6)

# tuple3 is the tuple with a list as an element


tuple3 = (10, 20, 30, [40, 50])
print(tuple3) # Output: (10, 20, 30, [40, 50])

# tuple4 is the tuple with a tuple as an element


tuple4 = (1, 2, 3, 4, 5, (10, 20))
print(tuple4) # Output: (1, 2, 3, 4, 5, (10, 20))

If there is only a single element in a tuple, the element should be followed by a comma. Without a
comma, it is treated as an integer. Sequences without parentheses are treated as tuples by default.
Correct way of assigning a single element:

[ ]: tuple5 = (20,)
print(tuple5) # Output: (20,)
print(type(tuple5)) # Output: <class 'tuple'>

Sequence without parentheses:

[ ]: seq = 1, 2, 3
print(seq) # Output: (1, 2, 3)
print(type(seq)) # Output: <class 'tuple'>

1
Chapter 10 Tuples and Dictionaries

10.1.1 Accessing Elements in a Tuple Elements of a tuple can be accessed using indexing
and slicing.
Examples:

[ ]: tuple1 = (2, 4, 6, 8, 10, 12)


print(tuple1[0]) # Output: 2
print(tuple1[3]) # Output: 8
# print(tuple1[15]) # Raises IndexError
print(tuple1[1 + 4]) # Output: 12
print(tuple1[-1]) # Output: 12

10.1.2 Tuple is Immutable Tuples are immutable, meaning their elements cannot be changed
after creation. Any attempt to modify an element results in an error.
Example:

[ ]: tuple1 = (1, 2, 3, 4, 5)
# tuple1[4] = 10 # Raises TypeError

# An element of a tuple can be of mutable type, such as a list


tuple2 = (1, 2, 3, [8, 9])
tuple2[3][1] = 10
print(tuple2) # Output: (1, 2, 3, [8, 10])

10.2 Tuple Operations 10.2.1 Concatenation Tuples can be joined using the concatenation
operator (+).
Examples:

[ ]: tuple1 = (1, 3, 5, 7, 9)
tuple2 = (2, 4, 6, 8, 10)
print(tuple1 + tuple2) # Output: (1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

tuple3 = ('Red', 'Green', 'Blue')


tuple4 = ('Cyan', 'Magenta', 'Yellow', 'Black')
tuple5 = tuple3 + tuple4
print(tuple5) # Output: ('Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow',␣
↪'Black')

10.2.2 Repetition The repetition operation (*) is used to repeat elements of a tuple.
Examples:

[ ]: tuple1 = ('Hello', 'World')


print(tuple1 * 3) # Output: ('Hello', 'World', 'Hello', 'World', 'Hello',␣
↪'World')

tuple2 = ("Hello",)
print(tuple2 * 4) # Output: ('Hello', 'Hello', 'Hello', 'Hello')

PRIMUS PU COLLEGE, BANGALORE | 2


Chapter 10 Tuples and Dictionaries

10.2.3 Membership The in operator checks if an element is present in the tuple, and the not in
operator checks if an element is absent.
Examples:

[ ]: tuple1 = ('Red', 'Green', 'Blue')


print('Green' in tuple1) # Output: True
print('Green' not in tuple1) # Output: False

10.2.4 Slicing Tuples support slicing to access a range of elements.


Examples:

[ ]: tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)


print(tuple1[2:7]) # Output: (30, 40, 50, 60, 70)
print(tuple1[:5]) # Output: (10, 20, 30, 40, 50)
print(tuple1[2:]) # Output: (30, 40, 50, 60, 70, 80)
print(tuple1[0:len(tuple1):2]) # Output: (10, 30, 50, 70)
print(tuple1[::-1]) # Output: (80, 70, 60, 50, 40, 30, 20, 10)

10.3 Tuple Methods and Built-in Functions Python provides various methods and functions
to work with tuples.

Method/Function Description Example


len() Returns the number of len((10, 20, 30))
elements in the tuple returns 3
tuple() Creates a tuple tuple([1, 2, 3])
returns (1, 2, 3)
count() Returns the count of a (10, 20,
specified element in the tuple 10).count(10)
returns 2
index() Returns the index of the first (10, 20,
occurrence of a specified 30).index(20)
element returns 1
sorted() Returns a sorted list of the sorted((3, 2, 1))
tuple’s elements returns [1, 2, 3]
min() Returns the smallest element min((10, 20, 30))
returns 10
max() Returns the largest element max((10, 20, 30))
returns 30
sum() Returns the sum of the sum((10, 20, 30))
elements returns 60

Experiment all the functions here

[ ]:

PRIMUS PU COLLEGE, BANGALORE | 3


Chapter 10 Tuples and Dictionaries

10.4 Tuple Assignment Tuples support a useful feature called tuple assignment, allowing mul-
tiple variables to be assigned values from a tuple simultaneously.
Example:

[ ]: (num1, num2) = (10, 20)


print(num1) # Output: 10
print(num2) # Output: 20

record = ("Pooja", 40, "CS")


(name, rollNo, subject) = record
print(name) # Output: Pooja
print(rollNo) # Output: 40
print(subject) # Output: CS

10.5 Nested Tuples A tuple inside another tuple is called a nested tuple.
Program 10-1: Creating a Nested Tuple

[ ]: st = ((101, "Aman", 98), (102, "Geet", 95), (103, "Sahil", 87), (104, "Pawan",␣
↪79))

print("S_No", " Roll_No", " Name", " Marks")


for i in range(0, len(st)):
print((i+1), '\t', st[i][0], '\t', st[i][1], '\t', st[i][2])

10.6 Tuple Handling Program 10-2: Swapping Two Numbers

[ ]: num1 = int(input('Enter the first number: '))


num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:", num1)
print("Second Number:", num2)
(num1, num2) = (num2, num1)
print("\nNumbers after swapping:")
print("First Number:", num1)
print("Second Number:", num2)

Program 10-3: Computing Area and Circumference of a Circle

[ ]: def circle(r):
area = 3.14 * r * r
circumference = 2 * 3.14 * r
return (area, circumference)

radius = int(input('Enter radius of circle: '))


area, circumference = circle(radius

)
print("\nArea:", area)

PRIMUS PU COLLEGE, BANGALORE | 4


Chapter 10 Tuples and Dictionaries

print("Circumference:", circumference)

10.7 Dictionaries A dictionary is an unordered collection of data in key-value pairs, defined


within curly braces. Keys are unique and immutable, whereas values can be any data type.
Examples:

[ ]: Dict = {'A': 65, 'B': 66, 'C': 67}


print(Dict) # Output: {'A': 65, 'B': 66, 'C': 67}

Creating an empty dictionary

[ ]: D = {}
print(D) # Output: {}

10.7.1 Accessing Elements of a Dictionary Elements of a dictionary can be accessed using


keys. Non-existing keys raise a KeyError.
Examples:

[ ]: Dict = {'M': 77, 'N': 78, 'O': 79}


print(Dict['O']) # Output: 79
# print(Dict['P']) # Raises KeyError

Dict1 = {0: 'Red', 1: 'Green', 2: 'Blue'}


print(Dict1[2]) # Output: Blue

10.7.2 Changing, Adding, and Deleting Dictionary Elements Dictionaries are mutable
Dictionary elements can be modified or deleted using keys.
Examples:

[ ]: Dict = {'M': 77, 'N': 78, 'O': 79}


print(Dict) # Output: {'M': 77, 'N': 78, 'O': 79}

# Changing a element
Dict['N'] = 92
print(Dict) # Output: {'M': 77, 'N': 92, 'O': 79}

#Adding a new element


Dict['P'] = 80
print(Dict) # Output: {'M': 77, 'N': 92, 'O': 79, 'P': 80}

#Deleting an element
del Dict['M']
print(Dict) # Output: {'N': 92, 'O': 79, 'P': 80}
# del Dict['M'] # Raises KeyError

#Deleting all the elements

PRIMUS PU COLLEGE, BANGALORE | 5


Chapter 10 Tuples and Dictionaries

Dict.clear()
print(Dict) # Output: {}

10.7.3 Dictionary Operations


• Membership operation
• Traversing Operation
Examples:

[ ]: dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print('Suhel' in dict1)

dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print('Suhel' not in dict1)

[ ]: dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}

#method 1
for key in dict1:
print(key,':',dict1[key])

#method 2
for key,value in dict1.items():
print(key,':',value)

10.8 Dictionary Methods and Built-in Functions Python provides various methods and
functions to work with dictionaries.

Method/Function Description Example


len() Returns the number of items len({'a': 1, 'b':
in the dictionary 2}) returns 2
dict() Creates a dictionary dict(a=1, b=2)
returns {'a': 1,
'b': 2}
keys() Returns a view object of the {'a': 1, 'b':
dictionary’s keys 2}.keys() returns
dict_keys(['a',
'b'])
values() Returns a view object of the {'a': 1, 'b':
dictionary’s values 2}.values() returns
dict_values([1,
2])
items() Returns a view object of the {'a': 1, 'b':
dictionary’s items 2}.items() returns
dict_items([('a',
1), ('b', 2)])

PRIMUS PU COLLEGE, BANGALORE | 6


Chapter 10 Tuples and Dictionaries

Method/Function Description Example


clear() Removes all items from the {'a': 1, 'b':
dictionary 2}.clear() results
in {}
get() Returns the value for a {'a': 1, 'b':
specified key 2}.get('a') returns
1
update() Updates the dictionary with {'a':
specified key-value pairs 1}.update({'b':
2}) results in {'a':
1, 'b': 2}

Experiment all the Methods and Buitl-in functions

[ ]:

Program 10-6 Write a program to enter names of employees and their salaries as input and store
them in a dictionary.

[ ]: ## # Program to create a dictionary which stores names of the employee


# and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])

Exercises 1. Write a program to read email IDs of n number of students and store
them in a tuple. Create two new tuples: one to store only the usernames from the
email IDs and the second to store domain names from the email IDs. Print all three
tuples at the end of the program. - Hint: You may use the function split().

[ ]:

2. Write a program to input names of n students and store them in a tuple. Also,
input a name from the user and find if this student is present in the tuple or not.

[ ]:

3. Write a Python program to find the highest 2 values in a dictionary.

[ ]:

PRIMUS PU COLLEGE, BANGALORE | 7


Chapter 10 Tuples and Dictionaries

4. Write a Python program to create a dictionary from a string:


• Note: Track the count of the letters from the string.
• Sample string: 'w3resource'
• Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2,
'o': 1}

[ ]:

5. Write a program to input your friends’ names and their phone numbers and store
them in the dictionary as the key-value pair. Perform the following operations
on the dictionary:
• Display the name and phone number of all your friends
• Add a new key-value pair in this dictionary and display the modified dictionary
• Delete a particular friend from the dictionary
• Modify the phone number of an existing friend
• Check if a friend is present in the dictionary or not
• Display the dictionary in sorted order of names

[ ]:

PRIMUS PU COLLEGE, BANGALORE | 8

You might also like