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()))
RomanusSlolf
Админ, отличный сайт, но не нашел форму обратной связи. Кому написать по сотрудничеству(покупка рекламы)?