Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Chapter Notes: Tuples and Dictionaries

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction to Tuples

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:

  • Tuple of Integers: tuple1 = (1, 2, 3, 4, 5) 
  • Tuple of Mixed Data Types: tuple2 = ('Economics', 87, 'Accountancy', 89.6) 
  • Tuple with a List: tuple3 = (10, 20, 30, [40, 50]) 
  • Tuple with Another Tuple: tuple4 = (1, 2, 3, 4, 5, (10, 20)) 

Note:

  • When creating a tuple with just one item, like (20), you need to add a comma, making it (20,), to avoid it being considered as a single integer.
  • Also, if you write a sequence of items without parentheses, like 1, 2, 3, it will be treated as a tuple by default.

Accessing Elements in a Tuple

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:

  •  tuple1 = (2, 4, 6, 8, 10, 12) 

Accessing Elements:

  •  tuple1[0]  : Returns the first element (2).
  •  tuple1[3]  : Returns the fourth element (8).

Error Handling:

  •  tuple1[15]  : Raises an IndexError because the index is out of range.

Using Expressions:

  •  tuple1[1 + 4]  : Returns the sixth element (12) because 1 + 4 = 5.

Negative Indexing:

  •  tuple1[-1]  : Returns the first element from the end (12).

Tuple is Immutable

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

Tuple Operations

Concatenation

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:

  • tuple1. (1, 3, 5, 7, 9)
  • tuple2. (2, 4, 6, 8, 10)
  • tuple1 + tuple2. This concatenates the two tuples
  • Output: (1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

Example:

  • tuple3. ('Red', 'Green', 'Blue')
  • tuple4. ('Cyan', 'Magenta', 'Yellow', 'Black')
  • tuple5. tuple3 + tuple4 # This stores the elements of tuple3 and tuple4
  • Output: ('Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black')

Extending Tuples:

  • We can also extend an existing tuple by using the concatenation operator. When we do this, a new tuple is created.
  • Example:tuple6. (1, 2, 3, 4, 5)
  • Appending a Single Element:tuple6. tuple6. (6,)
  • Output: (1, 2, 3, 4, 5, 6)
  • Appending Multiple Elements:tuple6. tuple6. (7, 8, 9)
  • Output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

Advantages of Using Tuples:

  • Performance: Iterating through a tuple is faster than iterating through a list because tuples are immutable.
  • Data Integrity: If you have data that should not change, storing it in a tuple ensures that it remains unchanged accidentally.

Repetition

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.

  • tuple * n

Parameters.

  • tuple. The first operand must be a tuple.
  • n. The second operand must be an integer, specifying the number of times to repeat the tuple elements.

Example.

  • Repeating a Tuple.
  • Let's say we have a tuple tuple1 containing the elements 'Hello' and 'World'.

>>> tuple1 = ('Hello', 'World')

  • Now, if we use the repetition operator*to repeat this tuple 3 times, we get:

>>> tuple1 * 3 ('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

Tuple with a Single Element.

  • If we have a tuple with a single element, such as tuple2 containing 'Hello' :

>>> tuple2 = ("Hello",)

  • Using the repetition operator to repeat this tuple 4 times would result in:

>>> tuple2 * 4 ('Hello', 'Hello', 'Hello', 'Hello')

Membership

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 

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)

Tuple Methods and Built-In Functions

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

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Tuple Assignment

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.

Example 10.3

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 .

Nested Tuples

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

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Tuple Handling

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?: 


9
8
10
12
15

The numbers in the tuple are: (9, 8, 10, 12, 15)
The maximum number is: 15
The minimum number is: 8

Introduction to Dictionaries

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:

  • A key is separated from its value by a colon (:).
  • Consecutive items are separated by commas.
  • Items are unordered, which means that the data may not be returned in the same order in which it was initially entered.

Creating a Dictionary

To create a dictionary in Python:

  • Items are separated by commas and enclosed in curly braces.
  • Each item consists of a key-value pair, with the key and value separated by a colon (:).
  • Keys in the dictionary must be unique and of an immutable data type, such as a number, string, or tuple.
  • Values can be of any data type and can be repeated.

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}

Accessing Items in a Dictionary

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

Dictionaries are mutable, which means that their contents can be changed after the dictionary has been created.

Adding a New Item

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}

Modifying an Existing Item

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}

Dictionary Operations

Membership Test:

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:

  • dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} 
  • 'Suhel' in dict1 would return True  because 'Suhel' is a key in the dictionary.

Negation Test:

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:

  • dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} 
  • 'Suhel' not in dict1  would return  False  because 'Suhel' is a key in the dictionary.

Traversing a Dictionary

You can access or traverse each item in a dictionary using a for loop.

  • For example:
  • dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} 

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:

  • Dictionary: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Code: for key in dict1:  print(key, ':', dict1[key]) 
  • Output: Mohan : 95
    Ram : 89
    Suhel : 92
    Sangeeta : 85

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:

  • Dictionary: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Code: for key, value in dict1.items():  print(key, ':', value) 
  • Output: Mohan : 95
    Ram : 89
    Suhel : 92
    Sangeeta : 85

Dictionary Methods and Built-In Functions

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:
Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Examples:

Using len()

  • Code: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Example: len(dict1)
  • Output:.

Using dict()

  • Code: pair1 = [('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]
  • Example: dict1 = dict(pair1)
  • Output: {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}

Using keys()

  • Code: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Example: dict1.keys()
  • Output: dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])

Using values()

  • Code: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Example: dict1.values()
  • Output: dict_values([95, 89, 92, 85])

Using items()

  • Code: dict1.items()
  • Output: dict_items([('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)])

Using get()

  • Code: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Example: dict1.get('Sangeeta')
  • Output: 85
  • Example: dict1.get('Sohan')
  • Output: None

Using update()

  • Code: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Code: dict2 = {'Sohan': 79, 'Geeta': 89}
  • Example: dict1.update(dict2)
  • Output: {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89}

Using del()

  • Code: dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • Example: del dict1['Ram']
  • Output: {'Mohan': 95, 'Suhel': 92, 'Sangeeta': 85}
  • Example: del dict1['Mohan']
  • Output: {'Suhel': 92, 'Sangeeta': 85}
  • Example: del dict1
  • Output: NameError: name 'dict1' is not defined

Using clear()

  • Code: dict1.clear()
  • Output: {}

Manipulating Dictionaries

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.

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Output:

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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
Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Output:

Enter a string: HelloWorld 
H : 1
e : 1 
l : 3 
o : 2 
W : 1
r : 1 
d : 1

The document Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Tuples and Dictionaries Chapter Notes - Computer Science for Class 11 - Humanities/Arts

1. What are tuples in Python and how are they different from lists?
Ans. Tuples in Python are immutable sequences, meaning that once they are created, their elements cannot be changed, added, or removed. This is different from lists, which are mutable and allow modifications. Tuples are defined using parentheses (e.g., `my_tuple = (1, 2, 3)`) while lists are defined using square brackets (e.g., `my_list = [1, 2, 3]`).
2. How can you perform tuple assignment in Python?
Ans. Tuple assignment in Python allows you to assign values to multiple variables in a single statement. For example, you can use `a, b = (1, 2)` to assign `1` to `a` and `2` to `b`. This syntax can also unpack values from a tuple into a specific number of variables as long as the number of variables matches the number of elements in the tuple.
3. What are some common operations you can perform on tuples?
Ans. Common operations on tuples include indexing, slicing, concatenation, and repetition. You can access elements using an index (e.g., `my_tuple[0]` gives the first element), slice tuples to obtain a sub-tuple (e.g., `my_tuple[1:3]`), concatenate tuples using the `+` operator, and repeat tuples using the `*` operator (e.g., `my_tuple * 2`).
4. What is a dictionary in Python and how is it structured?
Ans. A dictionary in Python is an unordered collection of key-value pairs. Each key is unique and is used to access its corresponding value. Dictionaries are defined using curly braces, with each key-value pair separated by a colon (e.g., `my_dict = {'name': 'John', 'age': 30}`). Keys can be of any immutable type, while values can be of any type.
5. How can you traverse and manipulate a dictionary in Python?
Ans. You can traverse a dictionary using a for loop to iterate through its keys, values, or both. For example, `for key in my_dict:` allows you to access each key, and `my_dict[key]` gives you the corresponding value. To manipulate dictionaries, you can add new key-value pairs (e.g., `my_dict['gender'] = 'male'`), update existing values, or delete items using the `del` statement.
Related Searches

Exam

,

Objective type Questions

,

Semester Notes

,

practice quizzes

,

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Free

,

study material

,

past year papers

,

Extra Questions

,

shortcuts and tricks

,

mock tests for examination

,

video lectures

,

ppt

,

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

pdf

,

Sample Paper

,

Summary

,

MCQs

,

Viva Questions

,

Previous Year Questions with Solutions

,

Important questions

,

Tuples and Dictionaries Chapter Notes | Computer Science for Class 11 - Humanities/Arts

;