Tuples and Dictionaries - Class 11 Computer Science - Chapter 10 - Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubt-solving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes - Tuples and Dictionaries | Class 11 NCERT | Computer Science
Understanding Tuples and Dictionaries: Class 11 Notes
Python's built-in data structures, tuples and dictionaries, are essential parts of the language, offering unique ways to store and manipulate data. Here is an in-depth guide to understanding these concepts for Class 11 students.
Understanding Tuples
Creating Tuples
A tuple is an ordered sequence of elements of different data types, such as integers, floats, strings, lists, or even tuples. Tuples are enclosed in parentheses and the elements are separated by commas.
### Tuple of integers
tuple1 = (1, 2, 3, 4, 5)
### Tuple of mixed data types
tuple2 = ('Economics', 87, 'Accountancy', 89.6)
If there is only a single element in a tuple, it should be followed by a comma. Otherwise, it will be treated as a different data type.
### Incorrect way of assigning a single element tuple
tuple3 = (20)
print(type(tuple3)) # Output:
### Correct way
tuple3 = (20,)
print(type(tuple3)) # Output:
Accessing Elements in a Tuple
Elements of a tuple can be accessed using indexing and slicing.
tuple1 = (2, 4, 6, 8, 10, 12)
print(tuple1[0]) # Output: 2
print(tuple1[-1]) # Output: 12
Immutable Nature of Tuples
Tuples are immutable, meaning their elements cannot be changed after creation. Attempting to modify a tuple will result in a TypeError
.
tuple1 = (2, 4, 6)
tuple1[1] = 10 # Raises an error
Tuple Operations
Concatenation: We can join tuples using the concatenation operator (
+
).
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
print(tuple1 + tuple2) # Output: (1, 2, 3, 4, 5, 6)
Repetition: Use the repetition operator (
*
) to repeat elements.
tuple1 = ('Hello', 'World')
print(tuple1 * 2) # Output: ('Hello', 'World', 'Hello', 'World')
Slicing: Slicing can be used to obtain a range of elements.
tuple1 = (10, 20, 30, 40, 50)
print(tuple1[1:3]) # Output: (20, 30)
Common Tuple Methods and Functions
len(): Returns the number of elements in the tuple.
tuple(): Converts a sequence into a tuple.
count(): Returns the count of a specified element.
index(): Returns the index of the first occurrence of an element.
min(): Returns the smallest element.
max(): Returns the largest element.
sum(): Returns the sum of all elements in a tuple (if they are numbers).
tuple1 = (10, 20, 30, 20)
print(len(tuple1)) # Output: 4
print(tuple1.count(20)) # Output: 2
Tuple Assignment
Tuple assignment allows multiple variables to be assigned values from a tuple simultaneously.
(a, b) = (10, 20)
print(a) # Output: 10
print(b) # Output: 20
Nested Tuples
A tuple inside another tuple is called a nested tuple.
nested_tuple = (1, 2, (3, 4))
print(nested_tuple[2][1]) # Output: 4
Practical Examples Using Tuples
Tuples are efficient and can be used in various scenarios like function returns, swapping values, and more.
Understanding Dictionaries
A dictionary in Python is a collection of key-value pairs where each key is unique.
Creating Dictionaries
Dictionaries are created with curly braces, containing key-value pairs separated by colons.
dict1 = {'Mohan': 95, 'Ram': 89}
print(dict1)
Accessing Items in a Dictionary
Items in a dictionary can be accessed using keys.
dict1 = {'Mohan': 95, 'Ram': 89}
print(dict1['Ram']) # Output: 89
Mutable Nature of Dictionaries
Dictionaries are mutable, allowing modification of values and addition or removal of items.
dict1['Ram'] = 90
dict1['Sita'] = 85
print(dict1)
Dictionary Operations
Membership: Check if a key exists.
print('Ram' in dict1) # Output: True
Traversing a Dictionary
You can traverse a dictionary using a for
loop.
for key, value in dict1.items():
print(key, value)
Common Dictionary Methods and Functions
len(): Number of items in the dictionary.
keys(): Returns a list of all keys.
values(): Returns a list of all values.
items(): Returns a list of key-value pairs.
get(): Returns the value for a specified key.
update(): Adds key-value pairs from another dictionary.
del: Deletes a specified item.
print(dict1.keys())
print(dict1.values())
Dictionary Manipulation
Dictionaries support various manipulations like adding, updating, and deleting elements.
dict1.update({'Ravi': 88})
del dict1['Ram']
print(dict1)
Practical Examples Using Dictionaries
Dictionaries are useful in cases where data needs to be labelled with unique keys, such as student records, configurations, and more.
Summary and Key Takeaways
Tuples are immutable sequences, primarily used for storing heterogeneous data and ensuring data integrity.
Dictionaries are mutable mappings that associate unique keys with values, making them excellent for fast lookups and dynamic data storage.
Additional Resources
This guide provides an extensive overview of tuples and dictionaries, enabling Class 11 students to grasp these fundamental concepts with ease.
🚀 Learn more about Notes with Chatterbot AI
Extra Questions - Tuples and Dictionaries | NCERT | Computer Science | Class 11
💡 Have more questions?
Ask Chatterbot AINCERT Solutions - Tuples and Dictionaries | NCERT | Computer Science | Class 11
Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1)) print(tuple1)
Let's evaluate each statement one by one for the given tuples:
tuple1 = (23, 1, 45, 67, 45, 9, 55, 45)
tuple2 = (100, 200)
Statement i:
print(tuple1.index(45))
This statement finds the index of the first occurrence of the value
45
intuple1
.Output:
2
Statement ii:
print(tuple1.count(45))
This statement counts the number of times the value
45
appears intuple1
.Output:
3
Statement iii:
print(tuple1 + tuple2)
This statement concatenates
tuple1
andtuple2
.Output:
(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
Statement iv:
print(len(tuple2))
This statement prints the length of
tuple2
.Output:
2
Statement v:
print(max(tuple1))
This statement prints the maximum value in
tuple1
.Output:
67
Statement vi:
print(min(tuple1))
This statement prints the minimum value in
tuple1
.Output:
1
Statement vii:
print(sum(tuple2))
This statement prints the sum of values in
tuple2
.Output:
300
Statement viii:
print(sorted(tuple1)) print(tuple1)
sorted(tuple1)
returns a new list of all items intuple1
in ascending order.tuple1
remains unchanged because tuples are immutable.Output:
[1, 9, 23, 45, 45, 45, 55, 67] (23, 1, 45, 67, 45, 9, 55, 45)
Summary
i.
print(tuple1.index(45))
→2
ii.
print(tuple1.count(45))
→3
iii.
print(tuple1 + tuple2)
→(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv.
print(len(tuple2))
→2
v.
print(max(tuple1))
→67
vi.
print(min(tuple1))
→1
vii.
print(sum(tuple2))
→300
viii.
print(sorted(tuple1)) print(tuple1)
→[1, 9, 23, 45, 45, 45, 55, 67] (23, 1, 45, 67, 45, 9, 55, 45)
Consider the following dictionary stateCapital: stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna","Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}
Find the output of the following statements:
i. print(stateCapital.get("Bihar"))
ii. print(stateCapital.keys())
iii. print(stateCapital.values())
iv. print(stateCapital.items())
v. print(len(stateCapital))
vi print("Maharashtra" in stateCapital)
vii. print(stateCapital.get("Assam"))
viii. del stateCapital["Rajasthan"] print(stateCapital)
Here are the outputs of the provided statements when executed on the dictionary stateCapital
:
stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna","Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}
i. print(stateCapital.get("Bihar"))
Output:
Patna
ii. print(stateCapital.keys())
Output:
dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
iii. print(stateCapital.values())
Output:
dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
iv. print(stateCapital.items())
Output:
dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])
v. print(len(stateCapital))
Output:
4
vi. print("Maharashtra" in stateCapital)
Output:
True
vii. print(stateCapital.get("Assam"))
Output:
None
viii. del stateCapital["Rajasthan"]; print(stateCapital)
Output:
{'AndhraPradesh': 'Hyderabad', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}
"Lists and Tuples are ordered". Explain.
Lists and Tuples are ordered because each element in these data structures has a fixed position (or index). This means that the order in which elements are added to the list or tuple remains the same throughout. You can access elements by their position, and the order of elements is maintained during insertion and retrieval.
Examples:
List Example:
my_list = [10, 20, 30, 40]
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
Tuple Example:
my_tuple = (50, 60, 70, 80)
print(my_tuple[1]) # Output: 60
print(my_tuple[3]) # Output: 80
Key Points:
Indexing: Both lists and tuples support indexing, which allows you to access elements based on their position.
Order Preservation: The order of elements is preserved, meaning elements are stored and retrieved in the sequence they were added.
Predictable Access: The element at the nth position will always be at the nth position, unless explicitly changed (in case of lists, since tuples are immutable).
In summary, the main characteristic of lists and tuples being ordered allows for consistent and predictable data access based on their indices.
With the help of an example show how can you return more than one value from a function.
To return more than one value from a function in Python, you can use tuples. Below is an example that defines a function arithmetic_operations
which returns the sum, difference, and product of two numbers.
# Function to compute sum, difference, and product of two numbers
def arithmetic_operations(a, b):
sum_val = a + b
diff_val = a - b
prod_val = a * b
return sum_val, diff_val, prod_val
# Example usage
x, y = 5, 3
sum_val, diff_val, prod_val = arithmetic_operations(x, y)
print(f"Sum: {sum_val}") # Output: Sum: 8
print(f"Difference: {diff_val}") # Output: Difference: 2
print(f"Product: {prod_val}") # Output: Product: 15
In this example:
The function
arithmetic_operations
takes two parametersa
andb
.It calculates the sum, difference, and product of the two numbers.
These three values are returned as a tuple.
The returned values are then unpacked into
sum_val
,diff_val
, andprod_val
when the function is called.
This is how you can return and handle multiple values from a function.
What advantages do tuples have over lists?
Tuples have several advantages over lists:
Immutability: Tuples are immutable, meaning their elements cannot be changed after creation. This provides a level of data integrity because the data remains constant.
Faster Iteration: Iterating through a tuple is generally faster than iterating through a list due to their immutability.
Memory Efficiency: Tuples consume less memory compared to lists, making them more efficient for storing large amounts of data that do not require modification.
Hashable: Tuples can be used as keys in dictionaries because they are hashable, unlike lists.
Protection of Data: Using tuples can protect data that shouldn’t be changed, which can be particularly useful in multi-threaded or parallel programming scenarios where data immutability may prevent race conditions and harder-to-track bugs.
These properties make tuples suitable for use cases where the data is not expected to be modified and performance is a priority.
When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.
In Python, tuples and dictionaries are used for different purposes based on their unique characteristics. Here's a brief look at when to use each data structure and their usefulness with examples:
When to Use Tuples
Immutability: Use tuples when you need a collection of elements that should not change throughout the program. For example, coordinates of a point, RGB color values, or fixed sets of options.
Ordered Collection: Use tuples when you need an ordered collection of items that can be accessed by their position. For example, storing (latitude, longitude) pairs.
Heterogeneous Data: Tuples are suitable for holding a collection of different data types. For example,
(student_name, student_id, student_grade)
.
Examples:
Coordinates:
coordinates = (34.0522, -118.2437)
RGB Color Values:
color_red = (255, 0, 0)
Heterogeneous Data:
student_info = ("John Doe", 12345, "A")
When to Use Dictionaries
Associative Array: Use dictionaries when you need a key-value pair mapping, which allows for efficient lookups, insertions, and deletions. Dictionaries are ideal for situations where you need to associate unique keys with values.
Unordered Collection: The order of elements doesn't matter and they should be accessed via keys, not positions.
Mutability: Use dictionaries for collections that may need to be modified, such as updating values, adding new key-value pairs, or deleting existing pairs.
Examples:
Storing Student Grades:
student_grades = {"John Doe": "A", "Jane Smith": "B", "Emily Davis": "A-"}
Configuration Settings:
config = {"theme": "dark", "version": 1.2, "features": ["feature1", "feature2"]}
Count Occurrences of Elements:
char_count = {} for char in "hello world": if char in char_count: char_count[char] += 1 else: char_count[char] = 1
Prove with the help of an example that the variable is rebuilt in case of immutable data types.
To prove that a variable is rebuilt in case of immutable data types, you can look at how tuples (an immutable data type) behave when attempting to modify them. When you modify a tuple, a new instance is created instead of altering the existing one. Here is an example:
# Tuple declaration
tuple1 = (1, 2, 3)
# Try to modify an element of tuple1
try:
tuple1[0] = 10
except TypeError as e:
print(e) # This will raise a TypeError because tuples are immutable
# Showing that we need to rebuild the tuple to "modify" it
tuple2 = tuple1 + (10,)
print("Original Tuple:", tuple1)
print("New Tuple after adding an element:", tuple2)
# Check if the memory addresses of tuple1 and tuple2 are different
print("Memory address of tuple1:", id(tuple1))
print("Memory address of tuple2:", id(tuple2))
Explanation:
Initialization:
tuple1 = (1, 2, 3)
creates a tupletuple1
.
Attempt to Modify:
Attempting to modify an element of
tuple1
usingtuple1[0] = 10
raises aTypeError
because tuples are immutable.
Rebuilding:
Instead of modifying, we create a new tuple
tuple2
by concatenatingtuple1
with(10,)
, effectively adding a new element and creating a new tuple.
Memory Addresses:
Usingid(tuple1)
andid(tuple2)
, you can see thattuple2
is stored at a different memory address, proving that it is a new instance.
TypeError
occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) # statement 1
>>> len(tuple1) # statement 2
The TypeError
occurs because tuple1
is defined incorrectly. When defining a single-element tuple, you must include a comma after the element, e.g., (5,)
. Without the comma, the parentheses are interpreted as grouping parentheses rather than defining a tuple, and tuple1
is considered an integer.
Here is the corrected version of the code:
>>> tuple1 = (5,) # statement 1
>>> len(tuple1) # statement 2
1
Now, tuple1
is a tuple with one element, and len(tuple1)
returns 1
without error.
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 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()]
# Function to split email IDs into usernames and domain names
def split_emails(email_tuple):
usernames = tuple(email.split('@')[0] for email in email_tuple)
domains = tuple(email.split('@')[1] for email in email_tuple)
return usernames, domains
# Input number of students
n = int(input("Enter number of students: "))
# Initialize an empty tuple to store email IDs
emails = tuple()
# Read email IDs
for i in range(n):
email = input(f"Enter email ID of student {i+1}: ")
emails += (email, )
# Split email IDs into usernames and domains
usernames, domains = split_emails(emails)
# Print all three tuples
print("Emails:", emails)
print("Usernames:", usernames)
print("Domains:", domains)
Explanation:
The function
split_emails
splits each email ID into a username and a domain and stores them in separate tuples.The program inputs the number of students and then reads their email IDs, storing them in a tuple called
emails
.The
split_emails
function is called to split theemails
tuple into usernames and domains.Finally, it prints the original
emails
tuple, theusernames
tuple, and thedomains
tuple.
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.
We can accomplish these by:
(a) writing a user defined function
(b) using the built-in function
Below is a Python program that performs the required tasks. Both approaches (using a user-defined function and using a built-in function) are provided.
Using a User-Defined Function
def check_student_in_tuple(students_tuple, student_name):
"""Function to check if a student is in the tuple."""
return student_name in students_tuple
# Input the number of students
n = int(input("Enter the number of students: "))
students = []
# Input the names of the students
for i in range(n):
name = input("Enter the name of student {}: ".format(i+1))
students.append(name)
# Convert the list to a tuple
students_tuple = tuple(students)
# Input the name to be searched
search_name = input("Enter the name you want to search: ")
# Check if the student is present
if check_student_in_tuple(students_tuple, search_name):
print(f"{search_name} is present in the tuple.")
else:
print(f"{search_name} is not present in the tuple.")
Using Built-in Function
# Input the number of students
n = int(input("Enter the number of students: "))
students = []
# Input the names of the students
for i in range(n):
name = input("Enter the name of student {}: ".format(i+1))
students.append(name)
# Convert the list to a tuple
students_tuple = tuple(students)
# Input the name to be searched
search_name = input("Enter the name you want to search: ")
# Check if the student is present using the 'in' operator
if search_name in students_tuple:
print(f"{search_name} is present in the tuple.")
else:
print(f"{search_name} is not present in the tuple.")
Both methods will:
Ask for the number of students.
Collect the names of the students and store them in a tuple.
Take a name input from the user and check if the name exists in the tuple.
Print whether the name is found in the tuple or not.
In the first method, a user-defined function check_student_in_tuple
is used to check the presence of the student's name. In the second method, the in-built in
operator is directly utilized to perform the check.
Write a Python program to find the highest 2 values in a dictionary.
Here's a Python program to find the highest 2 values in a dictionary:
def find_highest_two_values(dictionary):
# Check if the dictionary has at least two items
if len(dictionary) < 2:
return "The dictionary does not have enough values."
# Sort the dictionary values in descending order and get the top two
sorted_values = sorted(dictionary.values(), reverse=True)
highest_two_values = sorted_values[:2]
return highest_two_values
# Sample dictionary
sample_dict = {'a': 10, 'b': 55, 'c': 23, 'd': 76, 'e': 42}
highest_two = find_highest_two_values(sample_dict)
print("The highest two values are:", highest_two)
In this program:
The function
find_highest_two_values
takes a dictionary as an input.It checks if the dictionary has at least two items.
It sorts the values of the dictionary in descending order.
It retrieves the top two values from the sorted list.
It returns the two highest values.
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}
Here is a Python program to create a dictionary from a string and track the count of each letter:
def count_letters(string):
# Create an empty dictionary to store the letter counts
letter_counts = {}
# Loop through each character in the string
for char in string:
if char in letter_counts:
# If character is already in the dictionary, increment its count
letter_counts[char] += 1
else:
# If character is not in the dictionary, add it with a count of 1
letter_counts[char] = 1
return letter_counts
# Sample string
sample_string = 'w3resource'
# Call the function and store the result in a variable
result = count_letters(sample_string)
# Print the result
print(result)
Expected output:
{'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}
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:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
Here's a Python program that performs the required operations on a dictionary of friends' names and their phone numbers:
def display_all_friends(friends):
print("\nName\t\tPhone Number")
for name, phone in friends.items():
print(f"{name}\t\t{phone}")
def add_friend(friends, name, phone):
friends[name] = phone
print(f"\nAdded {name} with phone number {phone}.")
display_all_friends(friends)
def delete_friend(friends, name):
if name in friends:
del friends[name]
print(f"\nDeleted {name} from the dictionary.")
else:
print(f"\n{name} not found in the dictionary.")
display_all_friends(friends)
def modify_phone_number(friends, name, new_phone):
if name in friends:
friends[name] = new_phone
print(f"\nUpdated {name}'s phone number to {new_phone}.")
else:
print(f"\n{name} not found in the dictionary.")
display_all_friends(friends)
def check_friend(friends, name):
if name in friends:
print(f"\n{name} is present in the dictionary.")
else:
print(f"\n{name} is not present in the dictionary.")
def display_sorted_friends(friends):
sorted_friends = dict(sorted(friends.items()))
display_all_friends(sorted_friends)
friends = {}
num = int(input("Enter the number of friends: "))
for _ in range(num):
name = input("Enter friend's name: ")
phone = input("Enter friend's phone number: ")
friends[name] = phone
print("\nMenu:")
print("a) Display all friends")
print("b) Add a new friend")
print("c) Delete a friend")
print("d) Modify a friend's phone number")
print("e) Check if a friend is present")
print("f) Display friends in sorted order")
print("q) Quit")
while True:
choice = input("\nEnter your choice: ").lower()
if choice == 'a':
display_all_friends(friends)
elif choice == 'b':
name = input("Enter friend's name: ")
phone = input("Enter friend's phone number: ")
add_friend(friends, name, phone)
elif choice == 'c':
name = input("Enter the name of the friend to delete: ")
delete_friend(friends, name)
elif choice == 'd':
name = input("Enter the name of the friend to modify: ")
new_phone = input(f"Enter the new phone number for {name}: ")
modify_phone_number(friends, name, new_phone)
elif choice == 'e':
name = input("Enter the name of the friend to check: ")
check_friend(friends, name)
elif choice == 'f':
display_sorted_friends(friends)
elif choice == 'q':
break
else:
print("Invalid choice. Please choose a valid option.")
Explanation
Display all friends (a): Prints all key-value pairs in the dictionary.
Add a new friend (b): Adds a new entry to the dictionary.
Delete a friend (c): Removes a specific entry from the dictionary.
Modify a friend's phone number (d): Updates the value for a specific key in the dictionary.
Check if a friend is present (e): Checks if a key exists in the dictionary.
Display friends in sorted order (f): Prints the dictionary sorted by keys (names).
Quit (q): Exits the program.
💡 Have more questions?
Ask Chatterbot AI