Table of contents |
|
Introduction to Tuples |
|
Tuple Operations |
|
Tuple Assignment |
|
Tuple Handling |
|
Introduction to Dictionaries |
|
Traversing a Dictionary |
|
Manipulating Dictionaries |
|
A tuple is a collection of items that are ordered and can be of different types, like numbers, text, or even other lists and tuples. You can recognize a tuple by its round brackets (like this: ) and the items inside are separated by commas. For example, (1, 'apple', [2, 3]) is a tuple with an integer, a string, and a list.
Tuples are similar to lists and strings in that you can access their elements using an index, which starts from 0. So, in the tuple (10, 20, 30), 10 is at index 0, 20 is at index 1, and 30 is at index 2.
Here are some examples of different tuples:
Note:
You can access elements in a tuple using indexing and slicing, just like you would with a list or a string.
Indexing means getting a single item from the tuple using its position, while slicing means getting a part of the tuple.
Example
Initializing a Tuple:
Accessing Elements:
Error Handling:
Using Expressions:
Negative Indexing:
A tuple is a type of data that cannot be changed once it is created. This means that the items inside a tuple are fixed and cannot be altered. If you try to change an item in a tuple, you will get an error. For example:
tuple1[4] = 10
This will result in a TypeError: 'tuple' object does not support item assignment
However, it is possible for an item in a tuple to be of a mutable type, such as a list. For instance, consider the following tuple:
tuple2 = (1, 2, 3, [8, 9])
In this case, the fourth element of tuple2 is a list. You can modify the list element within the tuple like this:
tuple2[3][1] = 10
This modification will be reflected in tuple2, resulting in:
(1, 2, 3, [8, 10])
In Python, we can join tuples together using the concatenation operator, which is represented by the symbol +. This operation creates a new tuple that contains the elements of both tuples.
Example:
Example:
Extending Tuples:
Advantages of Using Tuples:
The repetition operation, represented by the symbol *, is used to repeat the elements of a tuple. This operation allows us to create a new tuple by repeating the original tuple's elements a specified number of times.
Syntax.
Parameters.
Example.
Let's say we have a tuple tuple1 containing the elements 'Hello' and 'World'.
>>> tuple1 = ('Hello', 'World')
>>> tuple1 * 3 ('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
Tuple with a Single Element.
>>> tuple2 = ("Hello",)
>>> tuple2 * 4 ('Hello', 'Hello', 'Hello', 'Hello')
in Operator: The in operator checks for the presence of an element within a tuple. If the element is found, it returns True
; otherwise, it returns False .
For example:
tuple1 = ('Red', 'Green', 'Blue')
'Green' in tuple1
Output: True
not in Operator: The not in operator checks if an element is not present in a tuple. If the element is absent, it returns True
; if the element is present, it returns False .
For example:
tuple1 = ('Red', 'Green', 'Blue')
'Green' not in tuple1
Slicing can be applied to tuples, similar to strings and lists. Here are some examples:
Example 1: Slicing a Tuple
tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)
# Elements from index 2 to index 6
print(tuple1[2:7])
Output: (30, 40, 50, 60, 70)
Example 2: Printing All Elements
print(tuple1[0:len(tuple1)])
Output: (10, 20, 30, 40, 50, 60, 70, 80)
Example 3: Slicing from Start
print(tuple1[:5])
Output: (10, 20, 30, 40, 50)
Example 4: Slicing to End
print(tuple1[2:])
Output: (30, 40, 50, 60, 70, 80)
Example 5: Slicing with Step Size
print(tuple1[0:len(tuple1):2])
Output: (10, 30, 50, 70)
Example 6: Negative Indexing
print(tuple1[-6:-4])
Output: (30, 40)
Example 7: Reversing a Tuple
print(tuple1[::-1])
Output: (80, 70, 60, 50, 40, 30, 20, 10)
Python offers a variety of functions specifically designed for working with tuples. Some of the most commonly used tuple methods and built-in functions are detailed in the following table.
Built-in functions and methods for tuples
Tuple assignment is a valuable feature in Python that enables the simultaneous assignment of multiple variables from a tuple. When using tuple assignment, a tuple of variables on the left side of the assignment operator can be assigned corresponding values from a tuple on the right side. It's important to ensure that the number of variables on the left matches the number of elements in the tuple on the right.
Example 1: Basic Tuple Assignment
In this example, we see how tuple assignment works by assigning values to multiple variables at once.
>>> (num1, num2) = (10, 20)
>>> print(num1) # Output: 10
>>> print(num2) # Output: 20
Example 2: Unpacking a Tuple
In this example, we unpack the values of a tuple into individual variables.
>>> record = ("Pooja", 40, "CS")
>>> (name, rollNo, subject) = record
>>> print(name) # Output: 'Pooja'
>>> print(rollNo) # Output: 40
>>> print(subject) # Output: 'CS'
Example 3: ValueError in Tuple Assignment
This example demonstrates what happens when there are not enough values to unpack in a tuple assignment.
>>> (a, b, c, d) = (5, 6, 8) # This will raise an error
ValueError: not enough values to unpack (expected 4, got 3)
Expression Evaluation in Tuple Assignment
If there is an expression on the right side of the assignment, the expression is evaluated first, and then the result is assigned to the tuple.
In this example, we are assigning values to the variables num3 and num4 using a tuple unpacking technique.
The expression (10+5, 20+5) creates a tuple with the values 15 and 25. These values are then unpacked and assigned to num3 and num4 respectively.
Output: num3 is assigned the value 15 , and num4 is assigned the value 25 .
A nested tuple refers to a tuple that is contained within another tuple. In the context of Program 10-1, where the roll number, name, and marks (in percentage) of students are stored in a tuple, a nested tuple can be used to store the details of multiple students.
Program: This is a program to create a nested tuple to store roll number, name and marks of students
Program: Write a program to swap two numbers without using a temporary variable.
#Program to swap 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)
Output:
Enter the first number: 5
Enter the second number: 10
Numbers before swapping:
First Number: 5
Second Number: 10
Numbers after swapping:
First Number: 10
Second Number: 5
Program: Write a program to compute the area and circumference of a circle using a function.
# Function to compute area and circumference of the circle.
def circle(r):
area = 3.14*r*r
circumference = 2*3.14*r
# returns a tuple having two elements area and circumference
return (area,circumference)
# end of function
radius = int(input('Enter radius of circle: '))
area,circumference = circle(radius)
print('Area of circle is:',area)
print('Circumference of circle is:',circumference)
Program: Write a program to input n numbers from the user. Store these numbers in a tuple. Print the maximum and minimum number from this tuple.
#Program to input n numbers from the user. Store these numbers #in a tuple. Print the maximum and minimum number from this tuple. numbers = tuple()
#create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
#it will assign numbers entered by user to tuple 'numbers'
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Output: How many numbers do you want to enter?:
5
9
8
10
12
15The numbers in the tuple are: (9, 8, 10, 12, 15)
The maximum number is: 15
The minimum number is: 8
In Python, a dictionary is a data type that falls under the category of mapping. It represents a collection of key-value pairs, where each key is associated with a specific value. The key-value pair is referred to as an item. In a dictionary:
To create a dictionary in Python:
Example:
#dict1 is an empty Dictionary created
#curly braces are used for dictionary
>>> dict1 = {}
>>> dict1 {}
#dict2 is an empty dictionary created using #built-in function
>>> dict2 = dict() >>> dict2
{}
#dict3 is the dictionary that maps names
#of the students to respective marks in
#percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict3 {'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}
In a sequence like a string, list, or tuple, we access items using indexing. However, in a dictionary, items are accessed using keys instead of their positions or indices. Each key acts as an index and is mapped to a value.
The following example shows how a dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'
In the above examples the key 'Ram' always maps to the value 89 and key 'Sangeeta' always maps to the value 85. So the order of items does not matter. If the key is not present in the dictionary we get KeyError.
Dictionaries are mutable, which means that their contents can be changed after the dictionary has been created.
To add a new item to an existing dictionary, you can simply assign a value to a new key, as shown in the example below:
>>> dict1 = { 'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85 }
>>> dict1[ 'Meena'] = 78
In this example, a new entry for 'Meena' with a score of 78 is added to the dictionary. The updated dictionary now looks like this:
Output:
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}
To modify an existing item in a dictionary, you can overwrite the value associated with a specific key. Here’s an example of how to change the marks of 'Suhel':
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,
'Sangeeta': 85}
The membership operator in checks if a specific key is present in the dictionary. If the key is found, it returns True
; otherwise, it returns False.
For example:
The not in operator checks if a key is not present in the dictionary. If the key is absent, it returns True ; if the key is present, it returns False.
For example:
You can access or traverse each item in a dictionary using a for loop.
Method 1
To print the keys and their corresponding values from a dictionary in Python, we can use a simple for loop. This method iterates through each key in the dictionary and prints the key along with its value. Here’s how it works:
Example:
Method 2
Another way to print the keys and values of a dictionary in Python is by using the items() method. This method returns a view object that displays a list of a dictionary's key-value tuple pairs. Here’s how it works:
Example:
Python offers a variety of built-in functions and methods specifically designed for working with dictionaries. These tools allow for efficient manipulation and retrieval of data stored in key-value pairs. Here’s an overview of some commonly used dictionary methods and built-in functions:
Examples:
Using len()
Using dict()
Using keys()
Using values()
Using items()
Using get()
Using update()
Using del()
Using clear()
In this chapter, we have learnt how to create a dictionary and apply various methods to manipulate it. The following programs show the application of those manipulation methods on dictionaries.
Program: Creating and Manipulating a Dictionary of Odd Numbers
(a) Creating the Dictionary
We start by creating a dictionary called ODD that contains odd numbers between 1 and 10. In this dictionary, the keys are decimal numbers, and the values are the corresponding numbers written in words.
(b) Displaying the Keys
To display the keys of the dictionary, we use the keys() method. This method returns a view object that displays a list of all the keys in the dictionary.
(c) Displaying the Values
To display the values of the dictionary, we use the values() method. This method returns a view object that displays a list of all the values in the dictionary.
(d) Displaying the Items
To display the items (key-value pairs) of the dictionary, we use the items() method. This method returns a view object that displays a list of tuples, where each tuple contains a key and its corresponding value.
(e) Finding the Length of the Dictionary
To find the length of the dictionary (i.e., the number of key-value pairs it contains), we use the len() function. This function returns the number of items in the dictionary.
(f) Checking for the Presence of a Key: 7
To check if the key 7 is present in the dictionary, we can use the in operator. This operator returns True if the key is found in the dictionary, and False otherwise.
(g) Checking for the Presence of a Key: 2
Similarly, to check if the key 2 is present in the dictionary, we use the in operator.
(h) Retrieving the Value for Key 9
To retrieve the value corresponding to the key 9, we use the get() method. This method takes a key as an argument and returns the corresponding value. If the key is not found, it returns None or a default value if provided.
(i) Deleting the Item with Key 9
To delete the item with key 9 from the dictionary, we use the del statement along with the dictionary name and the key in square brackets. This removes the key-value pair from the dictionary.
Example Output:
Initial Dictionary:. 1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine' }
Keys: [1, 3, 5, 7, 9]
Values: ['One', 'Three', 'Five', 'Seven', 'Nine']
Items: [(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9, 'Nine')]
Length:.
Check 7: True
Check 2: False
Value for Key 9: 'Nine'
After Deletion:. 1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven' }
Program: Write a program to enter names of employees and their salaries as input and store them in a dictionary.
Output:
Program: Write a program to count the number of times a character appears in a given string.
#Count the number of times a character appears in a given string
Output:
Enter a string: HelloWorld
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
33 docs|11 tests
|
1. What are tuples in Python and how are they different from lists? | ![]() |
2. How can you perform tuple assignment in Python? | ![]() |
3. What are some common operations you can perform on tuples? | ![]() |
4. What is a dictionary in Python and how is it structured? | ![]() |
5. How can you traverse and manipulate a dictionary in Python? | ![]() |