Lab 10 - Set, Tuple and Dictionary
Lab 10 - Set, Tuple and Dictionary
# Empty tuple
tuple = ()
print(tuple)
# nested tuple
tuple = ("cat", [100, 98, 65], (1, 2, 3))
print(tuple)
1. Use Index
# Accessing tuple elements using indexing
characters = ("p", "y", "t", "h", "o", "n")
print(characters[0])
print(characters[5])
2. Negative index
# Accessing tuple elements using indexing
characters = ("p", "y", "t", "h", "o", "n")
print(characters[-1])
Programming with Python
print(characters[-3])
3. Slicing
# Accessing tuple elements using slicing
tuple=("p", "y", "t", "h", "o", "n")
print(tuple[1:4])
print(tuple[:-5])
print(tuple[3:])
print(tuple[:])
setA = set()
setA = {}
print(learnABC)
2. Valid and invalid dictionary
Which one is the valid or invalid dictionary?
myData = {
1: "Python",
(1, 2): 1,
3: [1, 2, 3]
}
print(myData)
myData = {
1: "Python",
[1, 2]: "2, 3",
}
print(myData)
3. Duplicate in Dictionary
myData = {
1:"hello",2:22,2:22,3:"hello",3:33
}
print(myData)
myData = {
1:"hello",2:22,3:22,4:"hello",5:33
}
print(myData)
print(languages["bm"])
1. You were given a tuple with elements (2, 4, 5). You want to generate a total value from the
tuple elements. Write a Python program to unpack the tuple into several variables and display
the total value.
2. You were given a tuple named turtle = (1, “Hello”). Write a python program to
a. Add on item 5 using +
b. Add on item “single” using append ().
3. Write a Python program to convert a tuple of characters into a string.
4. Write a Python program to convert a list into tuple.
5. Write a Python program to check if the element exists between a tuple.
6. Given: tuple = (23, 45, 65, 78, 98, 9, 45, 56, 43). Write a Python program to reverse this tuple.
7. Given a set {1, 2, “Hello”, “Python”}. Write a Python program to iterate over the set.
8. Write a Python program to find element in setA but not in setB.
9. Write a Python program to convert string to set, set to list and set to tuple.
10. Using set, write a Python program to count number of vowels from given strings
“Programming with Python”.
11. Write a Python program to add an item (state: Kedah) into the dictionary. Given a
dictionary {name: “Amira”, “age”: 35}
12. From question 11 above, write a Python program to display all items in the dictionary
using loops.
13. Given a values numbers = {145, 100, 65, 79}, write a Python program to sum all the
values in the dictionary.
14. Given a dictionary keys and items myData = { 1:"hello",2:22,2:22,3:"hello",3:33}, write
a Python program to check if multiple keys exist in a dictionary.