In this training, you will learn to program with Python using practical examples. In this tutorial, you will learn how to use lists, tuples, and dictionaries.

1. Introduction

In the last tutorials, we have used variables that can store a single item of data in them. When you used the random.choice([“red”, “blue”, “green”]) line of code you are picking a random item from a list of possible options. This demonstrates that one item can hols several pieces of separate data, in this case a collection, of colors.

There are several ways that collections of data can be stored as a single item. Three of the simpler ones are :

  • Tuples
  • Lists
  • Dictionaries

2. Tuples

Once a tuple is defined, you cannot change what is stored in it. This means that when you write the program, you must specify what data is stored in the tuple and the data cannot be changed while the program is running. Tuples are usually used for menu items that do not need to be modified.


tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

3. Lists

The contents of a list can be changed while the program is running and lists are one of the most common ways to store a collection of data under one variable name in Python. The data in a list does not all have to be of the same data type. For example, the same list can store both strings and integers; however, this can cause problems later and is therefore not recommended.


list1 = ["apple", "banana", "cherry"]
print(sorted(list1)) # Displays list1 in alphabetical order but does not change the order of the original list 
list2 = [1, 5, 7, 9, 3]
print(len(list2)) # Print the number of items of list2
list3 = [True, False, False]
print(list3[2]) # Print the item 2 from list3

4. Dictionaries

The contents of a dictionary can also be modified during program execution. Each value is associated with an index or key that you can define to make it easier to identify each data item. This index will not change if other rows of data are added or deleted, unlike lists where the position of the elements can change and their index number will also change.


thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964 }
print(thisdict["brand"]) # Print the "brand" value of the dictionary:

5. Exercises


Write a Python program to calculate the average value of the numbers in a given tuple of tuples.


nums = ((5, 7, 8, 10), (14, 9, 25) , (151, 66, 71))

for tup in nums:
    aver = sum(tup)/len(tup)


Create a tuple containing the names of five countries and display the whole tuple. Ask the user to enter one of the countries that have been shown to them and then display the index number (i.e. position in the list) of that item in the tuple.


	countries = (“Spain”, “Japan”, “Australia”, “Morocco”, “France”, “Qatar”)
	country = input(“Enter one of the countries from above: “)
	print(country, “has index number “, countries.index(country))


Add to the last program the instructions to ask the user to enter a number and display the country in that position.


	countries = (“Spain”, “Japan”, “Australia”, “Morocco”, “France”, “Qatar”)
	country = input(“Enter one of the countries from above: “)
	print(country, “has index number “, countries.index(country))
	num = int(input(“Enter a number between 0 and 4: “)


Write a program to find tuples which have all elements divisible by K from a list of tuples.


test_list = [(12, 24, 6), (7, 11, 6), (18, 13, 21)]
print("The original list is : " + str(test_list))
K = 6

res_list = []

for sub in test_list:
    if all(ele % K == 0 for ele in sub):

print(K, "Multiple elements tuples : " + str(res_list))


Create a list of two sports. Ask the user what their favorite sport is and add this to the end of the list. Sort the list and display it.


	sports = [“tennis”, “football”]
	sports.append(input(“What is your favourite sport ?”))


Write a python program to interchange first and last elements in a list


	test_list = [15, 57, 8, 5, 58, 152]
	list_size = len(test_list)

	temp = test_list[0]
	test_list[0] = test_list[list_size - 1]
	test_list[list_size - 1] = temp



Create a list of four three-digit numbers. Display the list to the user, showing each item from the list on a separate line. Ask the user to enter a three-digit number. If the number they have typed in matches one in the list, display the position of that number in the list, otherwise display the message “That is not in the list”.


	nums = [255, 158, 678, 897, 632]
	for i in nums:
	select = int(input(“Enter a number from the above list”))
	if select in nums:
		print(select, “is in position”, nums.index(select))
		print(“That is not in the list”)


Write a python program to print even numbers in a list 


	list1 = []
	num = int(input("Enter number of elements in list: "))
	for i in range(1, num + 1):
    		ele= int(input("Enter elements: "))
	print("Smallest element is:", min(list1))
	print("Largest element is:", max(list1))


Write a python program to print even numbers in a list


	test_list = [120, 21, 22, 97, 66, 117]
	for num in test_list:
    		if num % 2 == 0:
        	print(num, end=" ")

EXO 10

Write a program python to extract words starting with K in String List


	test_list = ["Good", "I google it", "Goodbye", "Google"]
print("The original list is : " + str(test_list))
K = "g"
res_list = []
for sub in test_list:
    temp = sub.split()
    for ele in temp:
        if ele[0].lower() == K.lower():
print("The filtered elements : " + str(res_list))

EXO 11

Ask the user to enter the names of three people they want to invite to a party and store them in a list. After they have entered all three names, ask them if they want to add another. If they do, allow them to add more names until they answer “no”. When they answer “no”, display how many people they have invited to the party.


name1 = input("Enter a name of somebody you want to invite :")
name2 = input("Enter another name: ")
name3 = input("Enter a third name: ")

party_inv = [name1, name2, name3]

another = input("Do you want to inivite another (y/n): ")

while another == "y":
    newname = party_inv.append(input("Enter another name: "))
    another = input("Do you want to inivite another (y/n): ")

print("You have", len(party_inv), "people coming to your party")

selection = input("Enter one of the names: ")
print(selection, "is in position", party_inv.index(selection), "on the list")

stillcome = input("Do you still want them to come (y/n): ")

if stillcome == "n":


EXO 12

Ask the user to enter four of their favourite foods and store them in a dictionary so that they are indexed with numbers starting from 1. Display the dictionary in full, showing the index number and the item. Ask them which they want to get rid of and remove it from the list. Sort the remaining data and display the dictionary.


food_dictionary = {}

food_dictionary[1] = input("Enter a food you like")
food_dictionary[2] = input("Enter a food you like")
food_dictionary[3] = input("Enter a food you like")


dislike = int(input("Which of these do you want to get rid of? "))

del food_dictionary[dislike]





Админ, отличный сайт, но не нашел форму обратной связи. Кому написать по сотрудничеству(покупка рекламы)?


How to fix Photoshop PSD file.


If you spend your free time playing or learning how to play, what instrument do you face, which instrument is your favorite? In my opinion, the piano sounds the best and also has the highest scale among all instruments and sounds beautifully in it as chords. Please briefly justify why this particular instrument deserves to be called your favourite.


Los Angeles the best in World casino royale movie english subtitle download 320casino royale james bond netflix apkbus to spirit mountain casino blackjackclassy slots casino no deposit bonus codes project slayers007 casino royale watch online free streamingcasino royale audiobook youtube quehappy casino game witcher 3does lucky moose casino have slot machines at the gymcasino royale best youtubeclosest casino with slots to my location picturecasino royale download movie songscasino slot free download kmspicocasino bay city expressallure of the seas casino royale downloadcasino royale guy who cries blood eyegreen casino royale iocasino royale budget rentalcasino lemonade free slots casinoall slots casino iphone app 2022casino technology slot machines wotcasino royale costume designer diorcan casinos tighten up slot machines manufacturerscasino de maquinas cerca de mi robotcasino slot machine free game no lifecasino royale ost free download xbox choctaw casino and resort slots menu nadead rising 2 slot ranch casino music notesall slots casino contact details 2022casino royale parking costbrango casino download for android offlinedoes casino 580 have slot machines bonusescasino slots gif animatorcasino royale is a classic 80casino jax no deposit bonus new membercasino royale book for sale ukcasino royale hd 3850casino near turlock ca 53wcasino royal full movie hdcasino royale 2006 hd 720p english subtitles in englishcasino royale izle 1 sezoncasino slots play watch onlinecaesars slots free casino statue of liberty lifebest casino restaurant lake tahoegame vault casino online kzall out casino battle royale participants 2021 skachatcasino royale 1954 spark notes freecasino royale full hindi doubbed hd movie download 64casino at belmont park farecasino royale digital code calculatorcasino royale planet ocean elsa emilie


Los Angeles the best in World casinos near los angeles with slots best slot machinescasino rate card applicationcasino royale 1954 download legendado em portugueshon dah casino webcam testdoes livermore casino have slot machines real moneycasino royale hollywood movie hindi input toolscasino royale royal caribbean points incasino royale 2006 lake como whatsappdavinci diamonds casino slot pngcasino corpus christi tx j2betway casino slots no depositdoubledown casino slots on facebook iniciobiggest casino slot games spb rubig slot jackpots at casino arizona tucsonbuffalo slots free vegas casino slot machines bonusesgo fish casino no deposit bonus pointsmaquinas de casino retrocant prebuy casino chips royal caribbean airlinescasino royal free app inventorcaesars casino pokies slot machines & games comcasino royale free play free onlinecasino player magazine loosest slots real moneycasino royale movie online hd y245crazy slots casino free download kmspicocasino royale poker plaques for sale pretoria [url=]casino royale 1967 movie download 64[/url][url=]casino king no deposit bonus code[/url][url=]azimuth king casino price chanel[/url][url=]casino royale female costumes que[/url][url=]casinos in the inland empire war z[/url][url=]casino slot wins 2022 yil[/url][url=]casinos near hattiesburg ms visual c[/url][url=]casino slots free sign up bonus globus[/url][url=]casino royale code redeem[/url][url=]casino slot winning pic to text[/url][url=]casino royale casio 705[/url][url=]graton casino concert schedule tonight[/url][url=]desert diamond casino promo code all[/url][url=]casino royale collector's edition minecraft[/url][url=]download irish slots casino ru[/url][url=]best slots on huuuge casino no deposit[/url][url=]best free casino slot apps rackspace[/url][url=]casino demo slots machine[/url][url=]casino royale mkv english subtitles download[/url][url=]calgary casino hotel nairobi[/url][url=]casino royale nepal entry fee structure[/url][url=]casino royale iphone wallpaper google[/url][url=]casino royale posters for sale ru[/url][url=]casino in new mexico on i 40 45[/url][url=]ashanti and mya hard rock casino world[/url]

Log in to leave a reply

Related posts

Developing a Web Application with Django Part 1: Getting Started


Developing a Web Application with Django Part 2: Templates


Developing a Web Application with Django Part 3 : Models