Tuple
A tuple is a collection similar to a Python list. The primary difference is that we cannot modify a tuple once it is
created. (Tuples are “immutable”) ال يمكن تعديل محتواها
Tuples are another kind of sequence that functions much like a list - they have elements which are indexed starting at
0
Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string
Since Python does not have to build tuple structures to be modifiable, they are simpler and more efficient in terms of
memory use and performance than lists
So in our program when we are making “temporary variables” we prefer tuples over lists
Tuples are Comparable قابلة للمقارنة
We can take advantage of the ability to sort a list of tuples to get a sorted version of a dictionary
First we sort the dictionary by the key using the items() method and sorted() function
Functions: count , index
Tuple Characteristics
Tuples are:
Ordered - They maintain the order of elements.
Immutable - They cannot be changed after creation.
Allow duplicates - They can contain duplicate values.
Create a Python Tuple
numbers = (1, 2, -5)
print(numbers)
# Output: (1, 2, -5)
Access Tuple Items
Each item in a tuple is associated with a number, known as a index.
The index always starts from 0, meaning the first item of a tuple is at index 0, the second item is at index 1, and so on.
Access Items Using Index
Tuple Cannot be Modified
Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.
If we try to modify a tuple, we will get an error. For example,
Python Tuple Length
We use the len() function to find the number of items present in a tuple. For example,
Iterate Through a Tuple
We use the for loop to iterate over the items of a tuple. For example,
OUTPUT
Code Output
thistuple = ("apple", "banana", "cherry") ('apple', 'banana', 'cherry')
print(thistuple)
thistuple = ("apple", "banana", "cherry") 3
print(len(thistuple))
thistuple = ("apple",) <class 'tuple'>
print(type(thistuple))
thistuple = ("apple") <class 'str'>
print(type(thistuple))
tuple1 = ("apple", "banana", "cherry") ('apple', 'banana', 'cherry')
tuple2 = (1, 5, 7, 9, 3) (1, 5, 7, 9, 3)
tuple3 = (True, False, False) (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
(x, y) = (4, 'fred') 'fred'
print(y)
(a, b) = (99, 98) 99
print(a)
z = (5, 4, 3) Traceback:'tuple' object ال يمكن تعديل
z[2] = 0 does tuples عناصر
not support item
Assignment
z = (5, 4, 3) Traceback: ال يمكن استخدام
[Link]() AttributeError: 'tuple' tuples معsort
object has no attribute
'sort'
z = (5, 4, 3) AttributeError: 'tuple' ال يمكن استخدام
[Link](2) object has no attribute معappend
'append' tuples
z = (5, 4, 3) AttributeError: 'tuple' ال يمكن استخدام
[Link]() object has no attribute tuples معreverse
'reverse'
d = dict() dict_items([('a', 2), ('b', 4)])
d['a'] = 2
d['b'] = 4
tups = [Link]()
print(tups)
print((0, 1, 2) < (5, 1, 2)) True tuples المقارنة في
print((0, 1, 2000000) < (0, 3, 4)) True
print((4, 1, 4) < (2, 3, 4)) False
print(( 'Jones', 'Sally' ) < ('Jones', 'Sam')) True
tuple2 = (1, 5, 3) (5, 3)
print(tuple2[1:])
Multiple Choices
1. Which one of these is a tuple?
a. thistuple = ('apple', 'banana', 'cherry') Answer:a
b. thistuple = ['apple', 'banana', 'cherry']
c. thistuple = {'apple', 'banana', 'cherry'}
d. None
2. What is the primary difference between lists and tuples in Python?
a. Tuples are mutable, while lists are immutable
b. Tuples are immutable, while lists are mutable Answer: b
c. Both are mutable
d. Both are immutable
3. What happens if you attempt to sort a tuple directly in Python?
a. The tuple is sorted in place
b. An AttributeError is raised Answer: b
c. The tuple is sorted and returned as a new tuple
d. The tuple contents are modified
4. How can you sort a dictionary by its values in descending order?
a. Use sorted([Link]())
b. Convert the dictionary items into tuples of the form (value, key), and sort them with sorted()
Answer: b
c. Use the .sort() method directly on the dictionary
d. Dictionaries cannot be sorted
5. What is the output of the following code snippet?
x = (3, 2, 1)
y = sorted(x)
print(y)
a. (1, 2, 3)
b. [1, 2, 3] Answer: b
c. A TypeError
d. An AttributeError
Coding
1. Write a python code to sort a dictionary by values in descending order.
# Define the dictionary
data = {'a': 10, 'b': 1, 'c': 22}
# Create a list of tuples (value, key)
tmp = [(v, k) for k, v in [Link]()]
# Sort the list in descending order
tmp_sorted = sorted(tmp, reverse=True)
# Print the sorted list
print("Sorted by values in descending order:")
for val, key in tmp_sorted:
print(f"{key}: {val}")
2. Write a python code with function returning multiple values as a tuple(add, subtract, multiply, divide)
# Function returning multiple values as a tuple
def calculate(a, b):
return (a + b, a - b, a * b, a / b)
result = calculate(10, 5)
add, subtract, multiply, divide = result
print("Addition:", add) # Output: 15
print("Subtraction:", subtract) # Output: 5
print("Multiplication:", multiply) # Output: 50
print("Division:", divide) # Output: 2.0
Dictionaries
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any
data type and can be duplicated, whereas keys can’t be repeated and must be immutable.
A linear collection of key-value pairs lookup by "tag" or "key"
Dictionaries are Python’s most powerful data collection
Dictionaries allow us to do fast database-like operations in Python
Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by commas. For example,
The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the key and 'Berlin' is the value
assigned to it and so on.
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
Add Items to a Dictionary
We can add an item to a dictionary by assigning a value to a new key. For example,
Change Dictionary Items
Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring to its key. For
example,
Iterate Through a Dictionary
A dictionary is an ordered collection of items, therefore it maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.
Find Dictionary Length
We can find the length of a dictionary by using the len() function.
Python Dictionary Methods
clear() Removes all the elements from the dictionary
get() Returns the value of the specified key
We can use get() and provide a default value of zero when the key is not yet in the dictionary – and
then just add one
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
Searching in Dictionary
We can check whether a key exists in a dictionary by using the in and not in operators.
Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.
OUTPUT
thisdict = { {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
counts = {'a': 3, 'b': 2, 'c': 5} {'a': 3, 'b': 5, 'c': 5}
counts['b'] = [Link]('b', 0) + 3
print(counts)
thisdict = { Ford
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
thisdict = { {'brand': 'Ford', 'model': 'Mustang', 'year': 2020} يتم اخذ اخر
"brand": "Ford", قييمة اذا
"model": "Mustang", تكررت
"year": 1964, Key
"year": 2020 وليسvalue
}
print(thisdict)
thisdict = { 3 ال تحسبkey
"brand": "Ford", المكررة
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
thisdict = { 4
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"color": ‘black’
}
print(len(thisdict))
thisdict = { {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'uid': 2020} تحسبvalue
"brand": "Ford", المكررة
"model": "Mustang",
"year": 2020,
"uid": 2020
}
print(thisdict)
thisdict = { {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red',
"brand": "Ford", 'white', 'blue']}
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
thisdict = { <class 'dict'>
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
thisdict = dict(name = "John", age = {'name': 'John', 'age': 36, 'country': 'Norway'}
36, country = "Norway")
print(thisdict)
cabinet = dict()
cabinet['summer'] = 12
cabinet['fall'] = 3
cabinet['spring'] = 75
print(cabinet) {'summer': 12, 'fall': 3, 'spring': 75}
3
print(cabinet['fall']) 3
cabinet['fall'] = cabinet['fall'] + 2
print(cabinet) {'summer': 12, 'fall': 5, 'spring': 75}
ccc = dict() Traceback (most recent call last):
print(ccc['csev']) File "<stdin>", line 1, in <module>
KeyError: 'csev'
names = dict()
names['ahmad'] = 82
names['ali'] = 38
names['sami'] = 75
print('ahmad' in names) True
print('khaled' in names) False
thisdict = { Ford
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]('brand')
print(x)
thisdict = { None
"brand": "Ford", غيرKey
"model": "Mustang", موجوده
"year": 1964
}
x = [Link](‘color’)
print(x)
thisdict = { dict_keys(['brand', 'model', 'year']) keys ياخذ
"brand": "Ford", فقط
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
thisdict = { dict_values(['Ford', 'Mustang', 1964]) ياخذvalues
"brand": "Ford", فقط
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
thisdict = { dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', keys يلخد
"brand": "Ford", 1964)]) values
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
d = {1: 'Geeks', 2: 'For', 3:'Python'} 1 Geeks
for key,value in [Link](): 2 For
print(key,value) 3 Python
d = {1: 'Geeks', 2: 'For', 'age':22} 1
2
# Iterate over keys age
for key in d: Geeks
print(key) For
# Iterate over values 22
for value in [Link](): 1: Geeks
print(value) 2: For
for key, value in [Link](): age: 22
print(f"{key}: {value}")
Multiple Choices
1. Which one of these is a tuple?
a. x = ('apple', 'banana', 'cherry')
b. x = {'type' : 'fruit', 'name' : 'banana'} Answer:b
c. x = ['apple', 'banana', 'cherry']
d. None
2. What is the primary difference between lists and dictionaries?
a. Lists are mutable, while dictionaries are immutable
b. Lists are indexed by integers, while dictionaries are indexed by keys Answer:b
c. Lists can store only integers, while dictionaries can store any data type
d. Lists are unordered, while dictionaries are ordered
3. Which method checks if a key exists in a dictionary without raising an error?
a. find()
b. exists()
c. in operator
d. get() Answer: d
4. What is the output of the following code?
counts = {'a': 3, 'b': 2, 'c': 5}
counts['b'] = [Link]('b', 0) + 3
print(counts)
a. {'a': 3, 'b': 2, 'c': 5}
b. {'a': 3, 'b': 5, 'c': 5}
c. {'a': 3, 'b': 3, 'c': 5}
d. {'a': 3, 'b': 6, 'c': 5} Answer: d
5. What does the following code print?
data = {'x': 10, 'y': 20, 'z': 30}
for key, value in [Link]():
print(key, value)
a. ['x', 'y', 'z']
b. [10, 20, 30]
c. x 10, y 20, z 30 Answer: c
d. Error
6. Select the correct way to print Emma’s age.
student = {1: {'name': 'Emma', 'age': '27', 'sex': 'Female'},
2: {'name': 'Mike', 'age': '22', 'sex': 'Male'}}
a. student[0][1]
b. student[1]["age"] Answer: b
c. student[0]["age"]
d. None
7. In Python, Dictionaries are immutable
a. True Answer: a
b. False
8. Items are accessed by their position in a dictionary and All the keys in a dictionary must be of the same
type.
a. True
b. False Answer:b
9. Select the correct ways to get the value of marks key.
student = {
"name": "Emma",
"class": 9,
"marks": 75
}
a. m = [Link](2)
b. m = [Link]('marks') Answer: b
c. m = student[2])
d. m = student['marks'])
10. What is the output of the following code
dict1 = {"key1":1, "key2":2}
dict2 = {"key2":2, "key1":1}
print(dict1 == dict2)
a. True Answer:a
b. False
Coding
1. Write a python code to count word frequencies in a line of entered text by user.
line = input("Enter a line of text: ")
words = [Link]()
counts = {}
for word in words:
counts[word] = [Link](word, 0) + 1
print("Word counts:", counts)
2. Write a python code to Find the most common word in a text entered by user .
Input Example:
Enter Text: Python is powerfull language, I love Python . I don't like C# language. Python
is better
Output:
The most common word is Python with 3 occurrences.
file_content = input("Enter Text: ")
words = file_content.split()
counts = {}
for word in words:
counts[word] = [Link](word, 0) + 1
most_common_word = max(counts, key=[Link])
print("The most common word is " + str(most_common_word) + " with " +
str(counts[most_common_word]) + " occurrences.")
3. Write a python code for sorting a dictionary by keys, values and Sorting in descending
Order.
a. By Keys
# Sample dictionary
data = {'b': 2, 'a': 5, 'c': 1}
# Sorting by keys
sorted_by_keys = dict(sorted([Link]()))
print("Sorted by keys:", sorted_by_keys)
b. By Values
# Sample dictionary
data = {'b': 2, 'a': 5, 'c': 1}
# Define a helper function to extract the value
def value_extractor(item):
return item[1]
# Sorting by values
sorted_by_values = dict(sorted([Link](), key=value_extractor))
print("Sorted by values:", sorted_by_values)
c. Sorting in Descending Order
data = {'b': 2, 'a': 5, 'c': 1}
sorted_by_keys_desc = dict(sorted([Link](), reverse=True))
print("Sorted by keys (descending):", sorted_by_keys_desc)
4. Write a Python program to manage student marks using a dictionary. The program
should allow you to:
1) Add students and their marks.
2) Update marks for an existing student.
3) Display all students and their marks.
4) Find the student with the highest marks.
5) Calculate the average marks of the class.
Example Input/Output:
# Dictionary to store student marks
student_marks = {}
def add_student():
name = input("Enter student name: ")
if name in student_marks:
print("Student already exists.")
else:
marks = int(input("Enter marks: "))
student_marks[name] = marks
print("Added " + str(name) + " with " + str(marks) + " marks.")
def update_marks():
name = input("Enter student name to update: ")
if name in student_marks:
marks = int(input("Enter new marks: "))
student_marks[name] = marks
print("Updated " + str(name) + "'s marks to " + str(marks) )
else:
print("Student not found.")
def display_students():
if student_marks:
print("Students and their marks:")
for name, marks in student_marks.items():
print(name + "," + str(marks))
else:
print("No students found.")
def find_top_student():
if student_marks:
top_student = max(student_marks, key=student_marks.get)
print("Top student:" + str(top_student) + " with " +
str(student_marks[top_student]) + " marks." )
else:
print("No students found.")
def calculate_average():
if student_marks:
average = sum(student_marks.values()) / len(student_marks)
print(f"Average marks: {average:.2f}")
else:
print("No students found.")
def main():
while True:
print("\n--- Student Marks Management ---")
print("1. Add Student")
print("2. Update Marks")
print("3. Display All Students")
print("4. Find Top Student")
print("5. Calculate Average Marks")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_student()
elif choice == '2':
update_marks()
elif choice == '3':
display_students()
elif choice == '4':
find_top_student()
elif choice == '5':
calculate_average()
elif choice == '6':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
main()
5. Write a Python program to manage sales data using a dictionary. The program should allow
you to:
1) Add a salesperson's name, sales amount, and tax percentage.
2) Update sales data (sales amount and tax percentage) for an existing salesperson.
3) Display all sales data (salesperson name, sales amount, tax percentage, and tax amount).
4) Find the salesperson with the highest sales.
5) Calculate the total sales and total tax collected.
Example Input/Output:
--- Salesperson Data Management ---
1. Add Sales Data
2. Update Sales Data
3. Display All Sales Data
4. Find Top Salesperson
5. Calculate Total Sales and Tax
6. Exit
Enter your choice: 1
Enter salesperson name: Alice
Enter sales amount: 5000
Enter tax percentage: 10
Enter your choice: 1
Enter salesperson name: Bob
Enter sales amount: 7000
Enter tax percentage: 8
Enter your choice: 3
Salesperson Data:
Name: Alice, Sales Amount: 5000, Tax Percentage: 10%, Tax Amount: 500.0
Name: Bob, Sales Amount: 7000, Tax Percentage: 8%, Tax Amount: 560.0
Enter your choice: 4
Top salesperson: Bob with 7000 in sales.
Enter your choice: 5
Total sales: 12000.0
Total tax collected: 1060.0
ANSWER:
# Dictionary to store salesperson data
sales_data = {}
def add_salesperson():
name = input("Enter salesperson name: ")
if name in sales_data:
print("Salesperson already exists.")
else:
sales_amount = float(input("Enter sales amount: "))
tax_percentage = float(input("Enter tax percentage: "))
sales_data[name] = {"sales_amount": sales_amount, "tax_percentage": tax_percentage}
print(f"Added {name} with sales amount {sales_amount} and tax percentage
{tax_percentage}%.")
def update_salesperson():
name = input("Enter salesperson name to update: ")
if name in sales_data:
sales_amount = float(input("Enter new sales amount: "))
tax_percentage = float(input("Enter new tax percentage: "))
sales_data[name] = {"sales_amount": sales_amount, "tax_percentage":
tax_percentage}
print("Updated")
else:
print("Salesperson not found.")
def display_sales_data():
if sales_data:
print("Salesperson Data:")
for name, data in sales_data.items():
tax_amount = data["sales_amount"] * data["tax_percentage"] / 100
print(f"Name: {name}, Sales Amount: {data['sales_amount']}, Tax Percentage:
{data['tax_percentage']}%, Tax Amount: {tax_amount:.2f}")
else:
print("No sales data found.")
def find_top_salesperson():
if sales_data:
top_salesperson = max(sales_data, key=lambda name: sales_data[name]
["sales_amount"])
print(f"Top salesperson: {top_salesperson} with {sales_data[top_salesperson]
['sales_amount']} in sales.")
else:
print("No sales data found.")
def calculate_totals():
if sales_data:
total_sales = sum(data["sales_amount"] for data in sales_data.values())
total_tax = sum(data["sales_amount"] * data["tax_percentage"] / 100 for data in
sales_data.values())
print(f"Total sales: {total_sales:.2f}")
print(f"Total tax collected: {total_tax:.2f}")
else:
print("No sales data found.")
def main():
while True:
print("\n--- Salesperson Data Management ---")
print("1. Add Sales Data")
print("2. Update Sales Data")
print("3. Display All Sales Data")
print("4. Find Top Salesperson")
print("5. Calculate Total Sales and Tax")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_salesperson()
elif choice == '2':
update_salesperson()
elif choice == '3':
display_sales_data()
elif choice == '4':
find_top_salesperson()
elif choice == '5':
calculate_totals()
elif choice == '6':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
main()
6. Write a Python program to manage student marks using a dictionary. The program
should allow you to:
1) Enter student names and their marks.
2) Display all student names and their marks.
3) Find the student with the highest marks.
4) Find the student with the lowest marks.
5) Calculate the average marks of the class.
ANSWER:
# Dictionary to store salesperson data
sales_data = {}
def add_salesperson():
name = input("Enter salesperson name: ")
if name in sales_data:
print("Salesperson already exists.")
else:
sales_amount = float(input("Enter sales amount: "))
tax_percentage = float(input("Enter tax percentage: "))
sales_data[name] = {"sales_amount": sales_amount, "tax_percentage":
tax_percentage}
print(f"Added {name} with sales amount {sales_amount} and tax percentage
{tax_percentage}%.")
# Dictionary to store student marks
student_marks = {}
def enter_marks():
name = input("Enter student name: ")
if name in student_marks:
print("Student already exists. Use option 1 to overwrite marks.")
else:
marks = float(input("Enter marks: "))
student_marks[name] = marks
print(f"Added {name} with marks {marks}.")
def display_students():
if student_marks:
print("Students and their marks:")
for name, marks in student_marks.items():
print(f"{name}: {marks}")
else:
print("No students found.")
def find_highest_marks():
if student_marks:
top_student = max(student_marks, key=student_marks.get)
print(f"Student with the highest marks: {top_student}
({student_marks[top_student]})")
else:
print("No students found.")
def find_lowest_marks():
if student_marks:
low_student = min(student_marks, key=student_marks.get)
print(f"Student with the lowest marks: {low_student}
({student_marks[low_student]})")
else:
print("No students found.")
def calculate_average_marks():
if student_marks:
average = sum(student_marks.values()) / len(student_marks)
print(f"Average marks: {average:.2f}")
else:
print("No students found.")
def main():
while True:
print("\n--- Student Marks Management ---")
print("1. Enter Student Marks")
print("2. Display All Students and Marks")
print("3. Find Student with Highest Marks")
print("4. Find Student with Lowest Marks")
print("5. Calculate Average Marks")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
enter_marks()
elif choice == '2':
display_students()
elif choice == '3':
find_highest_marks()
elif choice == '4':
find_lowest_marks()
elif choice == '5':
calculate_average_marks()
elif choice == '6':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
main()
7. Python program that calculates the following from a given text file:
1) Character count
2) Word count
3) Line count
4) The number of times a specific word is repeated
5) Word frequencies.
Input/Output Example
Enter the filename (with extension): [Link]
Character count: 203
Word count: 31
Line count: 5
Enter the word to count: Python
The word 'Python' is repeated 4 times.
def calculate_counts(filename):
try:
with open(filename, 'r') as file:
text = [Link]()
# 1) Character count
char_count = len(text)
# 2) Word count
words = [Link]()
word_count = len(words)
# 3) Line count
[Link](0)
lines = [Link]()
line_count = len(lines)
print(f"Character count: {char_count}")
print(f"Word count: {word_count}")
print(f"Line count: {line_count}")
# 4) Count specific word occurrences
word_to_count = input("Enter the word to count: ").strip()
word_repeated_count = 0
for word in words:
if [Link]() == word_to_count.lower():
word_repeated_count = word_repeated_count +1
print(f"The word '{word_to_count}' is repeated {word_repeated_count}
times.")
words = [Link]()
# 5) Word frequencies
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
print("Word Frequencies:")
for word, count in word_counts.items():
print(f"{word}: {count}")
except FileNotFoundError:
print("The file was not found. Please check the filename and try again.")
except Exception as e:
print(f"An error occurred: {e}")
# Main function to run the program
def main():
filename = input("Enter the filename (with extension): ").strip()
calculate_counts(filename)
# Run the program
main()