04. Lists
04. Lists
Lists
Exercise 1 β First and last
Create a list containing five names.
Print:
- the first name
- the last name
- the third name
- the second-to-last name
Use both normal and negative indexes.
Exercise 2 β Shout the name
Create a list containing several names.
Ask the user for a number between 0 and the length of the list.
Print the corresponding name in uppercase.
For example:
Choose a number: 3
JOHNUse an index and .upper().
Exercise 3 β Add a name
Start with a list containing three names.
Ask the user for another name.
Add the name to the end of the list.
Then print the complete list and the number of names in the list.
Use .append() and len().
Exercise 4 β Insert a name
Start with:
["Alice", "Bob", "Charlie", "David"]Ask the user for a name.
Insert the new name at position 2.
Print the list before and after the insertion.
Then print the length of the list.
Exercise 5 β Remove a name
Start with a list containing five names.
Ask the user which name they want to remove.
If the name is in the list, remove it.
If it isn't in the list, print:
Name not foundFinally, print the remaining names.
Use in, not in, and .remove().
Exercise 6 β Shopping list
Create a small shopping list with three items.
Ask the user for two more items and add them to the list.
Then ask the user for one more item and insert it at the beginning of the list.
Print the final shopping list and the number of items.
Use both .append() and .insert().
Exercise 7 β Remove the last item
Create a list containing five numbers.
Remove the last number and store it in a variable.
Print:
Removed: 42
Remaining: [...]Then remove another number from the end.
Print the list again.
Use .pop().
Exercise 8 β List combinations
Create two lists:
["red", "green", "blue"]and
["yellow", "black", "white"]Create a new list containing all the colors from both lists.
Then create another list containing the colors from the first list repeated three times.
Print all three lists.
Use the + and * operators.
Exercise 9 β Parts of a list and a word
Create a list containing ten numbers.
Print:
- the first three numbers
- the last three numbers
- numbers 4 through 7
- the list in reverse order
Then create a string containing a word of your choice.
Print:
- the first three characters
- the last two characters
- the word backwards
Use slicing on both the list and the string.
Exercise 10 β Small contact list
Create a list containing several names.
The program should:
- Print the number of contacts.
- Ask the user for a name.
- Tell the user whether the name is in the list.
- If it is in the list, print its position.
- Ask the user for another name and add it to the list.
- Reverse the list.
- Print the final list.
Finally, clear the list and print its length.
Use len(), in, .index(), .append(), .reverse(), .clear() and == somewhere in the program.
Exercise 11 β Playlist manager
Start with a list containing five song titles.
Show the current playlist and ask the user what they want to do:
- Add a song
- Insert a song at a specific position
- Remove a song
- Remove the last song
- Show the first three songs
- Show the playlist in reverse order
- Clear the playlist
- Quit
After each operation, show the updated playlist.
If the user tries to remove a song that isn't in the playlist, display an appropriate message instead of crashing the program.
Exercise 12 β Exam scores
Create a list containing the scores of ten students.
Display:
- the number of students
- the highest score
- the lowest score
- the first five scores
- the last five scores
Then ask the user for a score and tell them how many students achieved exactly that score.
Finally, ask for another score and check whether that score occurs in the list.
If it does, display its first position in the list.
Exercise 13 β Shopping basket
Create an empty shopping basket.
Repeatedly ask the user for an item.
The user can:
- add an item
- remove an item
- remove the last item
- display the basket
- empty the basket
- finish shopping
When adding an item, check whether it is already in the basket.
If it is already there, tell the user instead of adding another copy.
When removing an item, handle the situation where the item doesn't exist.
When the user finishes, display:
- the complete basket
- the number of different items
- the first item
- the last item
Exercise 14 β Names and usernames
Create a list containing several people's full names.
For every name, display a simple username based on the person's name.
For example:
Alice Johnson β alicej
Peter Smith β peters
John Williams β johnwUse slicing to take part of the name.
Then ask the user for a name and check whether it is in the list.
If it is present, display its position.
Finally:
- add two new names
- remove one existing name
- reverse the list
- display the first half of the list
Try to make the program work with a list containing a different number of names as well.
Exercise 15 β Number statistics
Create a list containing twenty random integers between 1 and 100.
Display the complete list.
Then create a small report containing:
- the number of values
- the first value
- the last value
- the first five values
- the last five values
- how many times the number 50 occurs
- whether the number 25 occurs
- whether the number 75 does not occur
Next, ask the user for a number.
If that number occurs in the list, display its first position and how many times it occurs.
Finally, reverse the list and display it again.
Challenge: Try to make the report still work correctly if you change the number of generated values from 20 to 30.
Tuples
1. Favourite colours
Create a tuple containing five of your favourite colours.
- Print the complete tuple.
- Print the first colour.
- Print the last colour.
- Print how many colours are in the tuple.
2. A tuple of numbers
Create a tuple containing the numbers:
12, 7, 25, 4, 18, 9
- Print the largest and smallest number.
- Print the sum of all numbers.
- Print how many numbers are greater than 10.
Use a for loop for the last task.
3. Tuple slicing
Create the following tuple:
("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
Print:
- The first three days.
- The last three days.
- Every second day.
- The tuple in reverse order.
4. Searching a tuple
Create a tuple containing several usernames.
Ask the user for a username.
- Check whether the username occurs in the tuple.
- If it does, print its position in the tuple.
- If it does not, print a suitable message.
Do not use a list for the usernames.
5. Unpacking a tuple
Create a tuple containing the name, age and city of a person.
For example:
("Alice", 22, "Geel")
Unpack the tuple into three separate variables.
Then print a sentence containing the three values.
6. Tuple calculations
Create a tuple containing several temperatures in degrees Celsius.
Use a for loop to calculate:
- The average temperature.
- The number of temperatures below 0.
- The number of temperatures above 20.
Do not use statistics or another module.
7. Comparing two tuples
Create two tuples containing numbers.
For example:
(4, 8, 15, 16, 23, 42)
and
(4, 8, 15, 18, 23, 42)
Use a for loop to determine how many positions contain the same value.
Also print the positions where the values are different.
8. Convert a tuple
Create a tuple containing several names.
- Convert the tuple into a list.
- Add two new names to the list.
- Remove one name from the list.
- Convert the list back into a tuple.
- Print the resulting tuple.
9. Students and scores
Create a list containing tuples. Each tuple contains a student's name and their score.
For example:
[("Alice", 17), ("Bob", 12), ("Charlie", 8), ("Diana", 15)]
Use a for loop to:
- Print every student's name and score.
- Print only the students who passed.
- Calculate the average score.
10. Shopping list with prices
Ask the user for the names and prices of five products.
Store each product as a tuple containing its name and price, and put all tuples in a list.
For example:
[("Bread", 2.50), ("Milk", 1.20), ...]
Then use a for loop to:
- Print every product and its price.
- Calculate the total price.
- Find the most expensive product.
- Create a new list containing only the products that cost more than β¬5.
Bonus: Sort the list based on price.
Dictionaries
1. A student profile
Create a dictionary called student containing the following information:
- Name: Alex
- Age: 20
- Study programme: IT
- Year: 2
Print the student's name, age and study programme separately.
2. A simple phone book
Create a dictionary called phone_book containing three people and their phone numbers.
Print the phone number of one specific person. Then ask the user to enter a person's name and print their phone number.
3. β Product prices
Create a dictionary called prices containing five products and their prices.
Ask the user to enter a product name. Print the price of that product.
Then ask the user to enter the name of another product and print its price multiplied by 2.
4. Updating a dictionary
Create a dictionary called inventory containing three products and their stock quantities.
Perform the following operations:
- Print the current stock of one product.
- Change the stock of that product.
- Add a new product with its stock quantity.
- Remove one of the original products.
- Print the final dictionary.
5. A safer phone book
Start with a phone book containing three people and their phone numbers.
Ask the user to enter a name.
- If the name exists in the dictionary, print the phone number.
- If the name does not exist, print a message saying that the person is not in the phone book.
Use the in operator to check whether the key exists.
6. Product lookup
Create a dictionary containing five products and their prices.
Ask the user to enter a product name. If the product exists, print its price. Otherwise, print a message saying that the product is unavailable.
Afterwards, ask for another product name and repeat the lookup. You may assume that the user enters a valid product name the second time.
7. Counting points in a game
Create a dictionary called scores containing the names of three players and their scores.
Ask the user to enter a player's name and the number of points they have earned.
- If the player already exists, add the new points to their current score.
- If the player does not exist, add them to the dictionary with the entered number of points as their initial score.
Print the updated dictionary.
8. A list of students
Create an empty list called students.
Add three student dictionaries to the list. Each dictionary must contain a student's name, age and study programme.
Use append() to add the dictionaries to the list.
Print the entire list. Then print the name of the second student.
9. Adding students
Start with a list containing three student dictionaries. Each student has a name and an age.
Ask the user to enter the name and age of a new student. Create a dictionary for that student and add it to the list using append().
Print the complete list of students.
10. Finding a student
Create a list of at least four student dictionaries. Each dictionary contains a name, age and study programme.
Ask the user to enter a name.
- Use a
forloop to go through the list. - Check whether each student's name matches the entered name.
- If a match is found, print all information about that student.
- If no match is found, print an appropriate message.
You may use a Boolean variable to keep track of whether the student was found.
11. Students per course
Create a dictionary called courses in which each key is a course name and each value is a list of student names.
For example, a course could contain three students.
- Add at least three courses to the dictionary.
- Print the list of students for one specific course.
- Add another student to one of the existing courses using
append(). - Print the updated dictionary.
12. Adding students to courses
Start with a dictionary containing two courses, each with a list of students.
Ask the user to enter a course name and a student name.
- If the course already exists, add the student to its list using
append(). - If the course does not exist, create a new list containing that student and add it to the dictionary.
Print the resulting dictionary.
13. A shopping list per person
Create an empty dictionary called shopping_lists.
Ask the user to enter the names of three people. For each person, ask them to enter three items they want to buy.
Store each person's shopping items in a list inside the dictionary.
Then ask the user to enter a person's name and one additional item.
- If the person already has a shopping list, append the new item.
- If the person does not yet have a shopping list, create a new list containing the item.
Print the complete dictionary.
14. Course overview
Create a dictionary called courses. Each key is a course name, and each value is a list of student names.
Include at least three courses with different numbers of students.
Use nested for loops to print the information in the following format:
Programming:
- Alex
- Sam
- Taylor
Networking:
- Jordan
- Casey
Databases:
- Morgan
- Jamie
- RobinThe output must be generated from the dictionary, not printed as fixed text.
15. Student administration system
Create a list of dictionaries representing students. Each student dictionary must contain:
name: the student's nameage: the student's agecourses: a list of courses the student follows
Start with at least three students, each following at least two courses.
Your programme must then perform the following tasks:
- Print all students and their information in a readable format.
- Ask the user for a new student's name and age.
- Ask the user to enter three courses for the new student.
- Create a dictionary for the new student and add it to the list using
append(). - Ask the user for the name of an existing student and a new course.
- If the student exists, add the course to their list of courses using
append(). - If the student does not exist, print an appropriate message.
- Print the complete updated student administration, including each student's courses on separate lines.
Example output:
Student: Alex
Age: 20
Courses:
- Programming
- Networking
Student: Sam
Age: 21
Courses:
- Databases
- Web DevelopmentUse loops to print the information. Your programme should work with any number of students and any number of courses in the lists, rather than relying on fixed positions.