TUPLES IN PYTHON
→ A tuple is immutable data in Python.
→ It is the same as List.
→ Once defined elements of a tuple can't be altered or manipulated
a = () #--> Empty tuple
a = (1, ) #--> tuple with only one element needs a comma
a = (1, 7, 2) #--> tuple with more than one element
Tuples Methods
→ Consider the following tuple
a = (1, 7, 2)
1. Count():
→ This method will count the number of elements that occur in the given tuple.
a = (1, 7, 2)
print(a.count(1))
2. Index():
→ This method will return the index of the first occurrence of an element in the
given tuple.
a = (1, 7, 2)
print(a.index(1))
Practice Questions on Tuples
1. Create a tuple with five numbers and print the first, third, and fifth
elements.
Untitled 1
numbers = (10, 20, 30, 40, 50)
print(numbers[0]) # Output: 10
print(numbers[2]) # Output: 30
print(numbers[4]) # Output: 50
2. Given a tuple a = (4, 2, 3, 4, 5) , use the count() method to find how many times
the number 4 appears in the tuple.
a = (4, 2, 3, 4, 5)
print(a.count(4)) # Output: 2
3. Create a tuple of five colors and find the index of "blue" using the index()
method.
colors = ("red", "blue", "green", "yellow", "purple")
print(colors.index("blue")) # Output: 1
4. Write a program that creates a tuple of names ("Alice", "Bob", "Charlie") and
prints the index of "Charlie".
names = ("Alice", "Bob", "Charlie")
print(names.index("Charlie")) # Output: 2
5. Create a tuple with some repeated elements, then use count() to find how
many times a specified element appears in the tuple.
fruits = ("apple", "banana", "cherry", "apple", "banana")
print(fruits.count("banana")) # Output: 2
Untitled 2
Mixed Practice Questions (Lists and Tuples)
1. Create a list of five numbers and convert it to a tuple. Then, use count() to
check if any number appears more than once.
numbers_list = [1, 2, 3, 2, 5]
numbers_tuple = tuple(numbers_list)
print(numbers_tuple.count(2)) # Output: 2
2. Create a tuple of colors, convert it to a list, add a new color, then convert
it back to a tuple and print it.
colors_tuple = ("red", "blue", "green")
colors_list = list(colors_tuple)
colors_list.append("yellow")
colors_tuple = tuple(colors_list)
print(colors_tuple) # Output: ('red', 'blue', 'green', 'yellow')
3. Create a list of names ["Alice", "Bob", "Eve"] . Convert it to a tuple and find the
index of "Eve".
names_list = ["Alice", "Bob", "Eve"]
names_tuple = tuple(names_list)
print(names_tuple.index("Eve")) # Output: 2
DICTIONARIES IN PYTHON
→ Dictionary is a collection of key-value pairs.
→ Dictionaries are ordered collection of data items. They store multiple items in
a single variable. Dictionary items are key-value pairs that are separated by
commas and enclosed within curly brackets {}.
Untitled 3
#SYNTAX:
dic = {"Key" : "Value"
}
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
Accessing Dictionary items:
I. Accessing single values:
Values in a dictionary can be accessed using keys. We can access dictionary
values by mentioning keys either in square brackets or by using get method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible'))
#Output
Karan
True
II. Accessing multiple values:
We can print all the values in the dictionary using values() method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
#Output
dict_values(['Karan', 19, True])
III. Accessing keys:
Untitled 4
We can print all the keys in the dictionary using keys() method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
#Output
dict_keys(['name', 'age', 'eligible'])
IV. Accessing key-value pairs:
We can print all the key-value pairs in the dictionary using items() method.
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
#Output
dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])
Dictionary Methods
The dictionary uses several built-in methods for manipulation. They are listed
below:
update()
The update() method updates the value of the key provided to it if the item
already exists in the dictionary, else it creates a new key-value pair.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
Output:
Untitled 5
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}
Removing items from the dictionary:
There are a few methods that we can use to remove items from the dictionary.
clear():
The clear() method removes all the items from the list.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.clear()
print(info)
Output:
{}
pop():
The pop() method removes the key-value pair whose key is passed as a
parameter.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.pop('eligible')
print(info)
Output:
{'name': 'Karan', 'age': 19}
Untitled 6
popitem():
The popitem() method removes the last key-value pair from the dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
info.popitem()
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
del:
We can also use the del keyword to remove a dictionary item.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info['age']
print(info)
Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}
If the key is not provided, then the del keyword will delete the dictionary
entirely.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info
print(info)
Output:
Untitled 7
NameError: name 'info' is not defined
Practice Questions with Solutions
1. Create a dictionary to store information about a book with keys "title",
"author", and "year". Print the value of the "title" key.
python
Copy code
book = {"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1
960}
print(book["title"]) # Output: To Kill a Mockingbird
2. Given a dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} , use the get()
method to retrieve the value of the "city" key.
python
Copy code
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(person.get("city")) # Output: New York
3. Create a dictionary grades = {"Math": 90, "Science": 85, "English": 88} and use the
values() method to print all the grades.
python
Copy code
grades = {"Math": 90, "Science": 85, "English": 88}
print(grades.values()) # Output: dict_values([90, 85, 88])
4. Create a dictionary to store information about a student with keys
"name", "age", and "grade". Then add a new key "school" with the value
"High School" using the update() method.
python
Copy code
Untitled 8
student = {"name": "John", "age": 16, "grade": "10th"}
student.update({"school": "High School"})
print(student) # Output: {'name': 'John', 'age': 16, 'grade': '10th', 'schoo
l': 'High School'}
5. Given a dictionary info = {'name': 'Karan', 'age': 19, 'eligible': True} , remove the key
"eligible" using the pop() method and print the modified dictionary.
python
Copy code
info = {'name': 'Karan', 'age': 19, 'eligible': True}
info.pop("eligible")
print(info) # Output: {'name': 'Karan', 'age': 19}
6. Create a dictionary employee = {'name': 'Alex', 'position': 'Manager', 'salary': 50000} . Use
the items() method to print all key-value pairs in the dictionary.
python
Copy code
employee = {'name': 'Alex', 'position': 'Manager', 'salary': 50000}
print(employee.items()) # Output: dict_items([('name', 'Alex'), ('positio
n', 'Manager'), ('salary', 50000)])
Assignment Questions
1. Create a dictionary car with keys "brand", "model", and "year". Then
update the "year" to the current year (e.g., 2023) and print the updated
dictionary.
2. Given a dictionary product = {'name': 'Laptop', 'price': 800, 'stock': 50} , use the popitem()
method to remove the last key-value pair and print the modified dictionary.
3. Create a dictionary profile = {'username': 'john_doe', 'email': '[email protected]', 'age': 30} .
Use the keys() method to print all the keys in the dictionary.
4. Write a program to create a dictionary countries = {'USA': 'Washington, D.C.', 'France':
'Paris', 'Japan': 'Tokyo'} . Add a new country "India" with its capital "New Delhi"
Untitled 9
using the update() method.
5. Create a dictionary scores = {"Math": 95, "Science": 80, "History": 88} . Use the del
keyword to delete the "Science" key, then print the updated dictionary.
6. Given a dictionary inventory = {'apples': 30, 'bananas': 50, 'oranges': 20} , clear all items
using the clear() method and print the result.
Assignment Questions with Solutions
1. Create a dictionary car with keys "brand", "model", and "year". Then
update the "year" to the current year (e.g., 2023) and print the updated
dictionary.
python
Copy code
car = {"brand": "Toyota", "model": "Camry", "year": 2015}
car.update({"year": 2023})
print(car) # Output: {'brand': 'Toyota', 'model': 'Camry', 'year': 2023}
2. Given a dictionary product = {'name': 'Laptop', 'price': 800, 'stock': 50} , use the popitem()
method to remove the last key-value pair and print the modified
dictionary.
python
Copy code
product = {'name': 'Laptop', 'price': 800, 'stock': 50}
product.popitem()
print(product) # Output: {'name': 'Laptop', 'price': 800}
3. Create a dictionary profile = {'username': 'john_doe', 'email': '[email protected]', 'age': 30} .
Use the keys() method to print all the keys in the dictionary.
python
Copy code
Untitled 10
profile = {'username': 'john_doe', 'email': '[email protected]', 'age': 3
0}
print(profile.keys()) # Output: dict_keys(['username', 'email', 'age'])
4. Write a program to create a dictionary countries = {'USA': 'Washington, D.C.', 'France':
'Paris', 'Japan': 'Tokyo'} . Add a new country "India" with its capital "New Delhi"
using the update() method.
python
Copy code
countries = {'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Toky
o'}
countries.update({"India": "New Delhi"})
print(countries) # Output: {'USA': 'Washington, D.C.', 'France': 'Paris', 'J
apan': 'Tokyo', 'India': 'New Delhi'}
5. Create a dictionary scores = {"Math": 95, "Science": 80, "History": 88} . Use the del
keyword to delete the "Science" key, then print the updated dictionary.
python
Copy code
scores = {"Math": 95, "Science": 80, "History": 88}
del scores["Science"]
print(scores) # Output: {'Math': 95, 'History': 88}
6. Given a dictionary inventory = {'apples': 30, 'bananas': 50, 'oranges': 20} , clear all items
using the clear() method and print the result.
python
Copy code
inventory = {'apples': 30, 'bananas': 50, 'oranges': 20}
inventory.clear()
print(inventory) # Output: {}
Untitled 11