Sample Programs on Lists, Tuples, Sets, and Dictionaries:
1. Find the smallest and largest elements of a list
# creating an empty list
res_list = []
# prompting for the number of elements
num = int(input("How many elements in list? :"))
#loop to append each element entered by user to res_list
for x in range(num):
numbers = int(input('Enter number '))
res_list.append(numbers)
print("\nMaximum element in the list is :", max(res_list))
print("Minimum element in the list is :", min(res_list))
2. using list slicing to split the list to half
List1 = [1,'ABC', 2, 3, 'abc', 'XYZ', 4]
#offset of middle element is 2
print("The first half of the list", List1[:3])
print("The second half of the list", List1[3:])
3. swapping first & last items of a list - using indexing
List1 = ['XYZ', 'ABC', 'xyz', 'abc']
print("Original List:", str(List1))
List1[0], List1[-1] = List1[-1], List1[0]
#updated list
print("List after swapping:", str(List1))
4. Program to demonstrate negative indexing
languages = ['Python', 'Swift', 'C++']
# access the last item
print('languages[-1] =', languages[-1])
# access the third last item
print('languages[-3] =', languages[-3])
5. Adding element at specific index in a list:
fruits = ['apple', 'banana', 'orange']
print("Original List:", fruits)
fruits.insert(2, 'cherry')
print("Updated List:", fruits)
6. Program to find number of elements (length) of list:
cars = ['BMW', 'Mercedes', 'Tesla']
print('Total Elements:', len(cars))
7. Iterating through a List:
fruits = ['apple', 'banana', 'orange']
# iterate through the list
for fruit in fruits:
print(fruit)
8. Sample program on Tuple
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
# trying to modify a tuple
cars[0] = 'Nissan' # error
print(cars)
9. Iterating through Tuple:
fruits = ('apple','banana','orange')
# iterate through the tuple
for fruit in fruits:
print(fruit)
10. Converting Tuple to String:
tup = ('e', 'x', 'e', 'r', 'c', 'i', 's', 'e', 's')
# Use the 'join' method to concatenate the characters in the tuple without any spaces and create
a single string
str = ''.join(tup)
print(str)
11. Python program to get 4th Element from Tuple:
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print(tuplex)
# Get the 4th element of the tuple (index 3)
item = tuplex[3]
print(item)
# Get the 4th element from the end of the tuple (index -4)
item1 = tuplex[-4]
print(item1)
12. Example program to demonstrate creation of Sets
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
13. Creating an empty set in Python:
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python.
To make a set without any elements, we use the set() function without any argument.
# create an empty set
empty_set = set()
# create an empty dictionary
empty_dictionary = { }
# check data type of empty_set
print('Data type of empty_set:', type(empty_set))
# check data type of dictionary_set
print('Data type of empty_dictionary:', type(empty_dictionary))
14. Adding items to set in Python:
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
# using add() method
numbers.add(32)
print('Updated Set:', numbers)
15. Remove an element from Set:
languages = {'Swift', 'Java', 'Python'}
print('Initial Set:',languages)
# remove 'Java' from a set
removedValue = languages.discard('Java')
print('Set after remove():', languages)
16. Program to create a dictionary:
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
# printing the dictionary
print(country_capitals)
17. Program to demonstrate how to access Dictionary:
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
# access the value of keys
print(country_capitals["Germany"]) # Output: Berlin
print(country_capitals["England"]) # Output: London
18. Adding items to a Dictionary:
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
# add an item with "Italy" as key and "Rome" as its value
country_capitals["Italy"] = "Rome"
print(country_capitals)
19. Removing Dictionary Items:
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
# delete item having "Germany" key
del country_capitals["Germany"]
print(country_capitals)
If we need to remove all items from a dictionary at once, we can use the clear() method.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
# clear the dictionary
country_capitals.clear()
print(country_capitals)
20. Changing Dictionary Items:
country_capitals = {
"Germany": "Berlin",
"Italy": "Naples",
"England": "London"
}
# change the value of "Italy" key to "Rome"
country_capitals["Italy"] = "Rome"
print(country_capitals)
21. Iterating through Dictionary:
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome"
}
# print dictionary keys one by one
for country in country_capitals:
print(country)
print()
# print dictionary values one by one
for country in country_capitals:
capital = country_capitals[country]
print(capital)
22. Finding Dictionary Length:
country_capitals = {"England": "London", "Italy": "Rome"}
# get dictionary's length
print(len(country_capitals)) # Output: 2
numbers = {10: "ten", 20: "twenty", 30: "thirty"}
# get dictionary's length
print(len(numbers)) # Output: 3
countries = {}
# get dictionary's length
print(len(countries)) # Output: 0
Lab-05:
import random
n=int(input("Enter number of times to get random numbers: "))
a,b=map(int,input("Enter range: ").split())
lis=list()
ran=dict()
for i in range (n):
lis.append(random.randint(a,b))
for i in lis:
ran[i]=lis.count(i)
print("Random numbers generated: ",lis)
print("Occurence of each element: ",ran)
Lab-07:
emp=dict()
n=int(input("enter the no. of employees:"))
for i in range(n):
print()
eno=int(input("Enter employee no:"))
ename=input("Enter employee name: ")
emp[eno]=list()
emp[eno].append(ename)
print("Employee details:")
print(emp)
print()
for i in emp:
hrs=int(input("Enter no. of hours worked:"))
if hrs>40:
overtime=hrs-40
otpay=overtime*12
else:
overtime=0
otpay=0
emp[i].extend([overtime,otpay])
print("Updated employee details: ")
print("Emp no\t\tdetails (Name,overtime,otpay)")
for i in emp:
print(i,"\t\t",emp[i])
Lab-09:
import random
b=set()
count=0
for i in range(10):
r=random.randint(15,45)
b.add(r)
print("Elements in the set: ",b)
for i in set(b):
if(i<=30):
count+=1
elif(i>35):
b.remove(i)
print("Elements after deteleing >35: ",b)
print("Count of no. <30 = ",count)
Lab-10:
def fact(x):
if x<1:
return 1
else:
return x*fact(x-1)
n=int(input("Enter no. of elements: "))
lis=list()
print("Enter elements: ")
for i in input().split(" "):
lis.append(int(i))
fac=list(map(fact,lis))
print("Entered no's are: ",lis)
print("Corresponding factorial no's are: ",fac)