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.

Example:

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.

Example

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.

Example:

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

5. Exercises

EXO 1

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

Response.

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

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

EXO 2

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.

Response

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

EXO 3

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

Response

	countries = (“Spain”, “Japan”, “Australia”, “Morocco”, “France”, “Qatar”)
	print(countries)
	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: “)
	print(countries[num])

EXO 4

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

Response

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):
        res_list.append(sub)

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

EXO 5

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.

Response

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

EXO 6

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

Response

	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

	print(test_list)

EXO 7

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”.

Response

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

EXO 8

Write a python program to print even numbers in a list 

Response

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

EXO 9

Write a python program to print even numbers in a list

Response

	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

Response

	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():
            res_list.append(ele)
 
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.

Response


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")
print(party_inv)

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":
    party_inv.remove(selection)

print(party_inv)

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.

Response

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")

print(food_dictionary)

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

del food_dictionary[dislike]

print(sorted(food_dictionary.values()))

 

13 comments

RomanusSlolf

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

Michaeldrete

How to fix Photoshop PSD file.

Stroiciel

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.

KeithEroxy

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

KeithEroxy

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=https://j9gambling.site]casino royale 1967 movie download 64[/url][url=https://j9gambling.site]casino king no deposit bonus code[/url][url=https://j9gambling.site]azimuth king casino price chanel[/url][url=https://j9gambling.site]casino royale female costumes que[/url][url=https://j9gambling.site]casinos in the inland empire war z[/url][url=https://j9gambling.site]casino slot wins 2022 yil[/url][url=https://j9gambling.site]casinos near hattiesburg ms visual c[/url][url=https://j9gambling.site]casino slots free sign up bonus globus[/url][url=https://j9gambling.site]casino royale code redeem[/url][url=https://j9gambling.site]casino slot winning pic to text[/url][url=https://j9gambling.site]casino royale casio 705[/url][url=https://j9gambling.site]graton casino concert schedule tonight[/url][url=https://j9gambling.site]desert diamond casino promo code all[/url][url=https://j9gambling.site]casino royale collector's edition minecraft[/url][url=https://j9gambling.site]download irish slots casino ru[/url][url=https://j9gambling.site]best slots on huuuge casino no deposit[/url][url=https://j9gambling.site]best free casino slot apps rackspace[/url][url=https://j9gambling.site]casino demo slots machine[/url][url=https://j9gambling.site]casino royale mkv english subtitles download[/url][url=https://j9gambling.site]calgary casino hotel nairobi[/url][url=https://j9gambling.site]casino royale nepal entry fee structure[/url][url=https://j9gambling.site]casino royale iphone wallpaper google[/url][url=https://j9gambling.site]casino royale posters for sale ru[/url][url=https://j9gambling.site]casino in new mexico on i 40 45[/url][url=https://j9gambling.site]ashanti and mya hard rock casino world[/url]

NathanBrold

Best [url=https://is.gd/u5Hkob]online casinos[/url] in the US of 2023. We compare online casinos, bonuses & casino games so that you can play at the best casino online in the USA Check out the best [url=https://is.gd/u5Hkob]new casino sites[/url] for 2023 that are ranked according to their casino game variety, bonus ease, safety, and overall user experience Find the [url=https://casino2202.blogspot.com/2023/09/best-9-online-casinos-for-real-money.html]best online casinos USA[/url] to play games for real money. List of the top US Casinos that accept US players. United States' leading gambling sites 2023 The [url=https://is.gd/AX10bn]best online casinos[/url] for players. We rundown the top 19 real money casinos with the best bonuses that are legit and legal to play at for players Find the [url=https://is.gd/sRrRLy]best online casinos USA[/url] to play games for real money. List of the top US Casinos that accept US players. United States' leading gambling sites 2023

Andrewdap

Nicely put. Many thanks! [url=https://c.cheapbuyorder.co.uk/categories/Depression/Emsam]buy emsam online[/url] Wow, attractive site. Thnx ... [url=https://c.cheapbuyorder.co.uk/categories/Depression/Emsam]buy emsam[/url] Just on the internet checking things out ... adore the pictures! I attempt to find out by looking at various other images, too.

Andrewdap

You have made your position quite effectively!! [url=https://c.cheapbuyorder.co.uk/categories/Allergies/Benadryl]buy benadryl online[/url] I love this website - its so usefull and helpfull. [url=https://c.cheapbuyorder.co.uk/categories/Allergies/Benadryl]buy benadryl[/url] I'm keen on the shades.

CliffUtist

Всем привет :) Рады вам представить Фанат-группу "[url=https://www.google.com/search?client=firefox-b-d&q=dj+juristar] Русские хиты германии [/url]" – ваш источник последних треков и горячих новинок от талантливых русских музыкантов германии. Например новый ремикс: [url=https://russischedjs.blogspot.com/2024/01/sektor-gaza-30-let-remix-dj-juri-star.html] DJ Juri Star - Сектор газа - 30 лет - Remix [/url] или [url=https://www.youtube.com/watch?v=JbOIzxKCYjQ] группа New Russian feat. Жека - Будешь моя [/url] Мы стремимся представлять самые захватывающие моменты в мире русской музыки германии, приглашая вас на захватывающее музыкальное путешествие. Мы следим за последними тенденциями и подбираем для вас только лучшие композиции, чтобы ваше знакомство с новой русской музыкой германии было насыщенным и увлекательным. "[url=https://www.youtube.com/channel/UC6QGPTqYq-JoLgzRxfGZaig] New Russian [/url] Music" – это сообщество музыкальных энтузиастов. Присоединяйтесь к нам, чтобы быть в курсе самого свежего звучания российской музыки. Дайте музыке войти в вашу жизнь. Мы всегда на высоте - Просто задаём в гугл: "Русские хиты германии"

Robertoquort

Hey everyone! I've just stumbled upon an amazing resource that's all about cryptocurrency exchanges. If you're keen on exploring different cryptocurrency exchanges, this might be the perfect spot for you! The site (https://cryptoairdrops.ru/) offers detailed reviews of various crypto exchanges, including the ins and outs of their trading platforms, security protocols, supported coins, and overall reliability. Whether you're a novice just starting out or an experienced trader, there's something for everyone. What I found particularly useful was their side-by-side comparisons, which made it super easy to assess different exchanges and find the one that best fits my needs. They also cover the latest developments in the crypto world, which keeps you informed on all the latest happenings. If you're interested in getting into crypto trading, I highly recommend checking this site out. It's packed with valuable information that can help you make informed decisions in the ever-changing world of cryptocurrency. Let's dive into it and help each other out! Would love to hear your thoughts and experiences with different exchanges as well.

magJippaurocauct

Be free in your desires, night games. [URL=https://datesnow.life]Authentic Ladies[/URL]

RobertVed

Amcv.ro - [url=https://www.google.kz/url?sa=t&url=https%3A%2F%2Famcv.ro/] Marketing de continut prin storytelling[/url] - Platforma unde creativitatea si promovarea se intalnesc pentru a da viata afacerilor tale! Ne-am propus sa oferim o platforma unica si eficienta pentru cei interesati sa-si promoveze afacerile, produsele sau serviciile prin intermediul advertorialelor personalizate si a articolelor de promovare. Suntem aici pentru a va ajuta sa va faceti vocea auzita in lumea online, sa va conectati cu audienta tinta si sa va evidentiati in fata competitorilor. Indiferent daca aveti o afacere mica sau una mai mare, Amcv.ro este locul potrivit pentru a va face cunoscut mesajul. Cu noi, puteti posta advertoriale personalizate care sa reflecte in mod autentic valorile si misiunea afacerii dumneavoastra. Fie ca sunteti in domeniul comertului, al serviciilor sau al productiei, exista mereu un spatiu pentru dumneavoastra pe Amcv.ro.

magJippaurocauct

Embrace the freedom of casual encounters on the best dating app in town! Verified Maidens [URL=https://datesnow.life]Supreme casual Dating[/URL]

Log in to leave a reply

Related posts

Developing a Web Application with Django Part 1: Getting Started

1/12/2021

Developing a Web Application with Django Part 2: Templates

15/12/2021

Developing a Web Application with Django Part 3 : Models

7/1/2022