Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Lahore Grammar School

Paragon City

Python List Data Types Worksheet

List Data Type

A list is a collection of items that are ordered and changeable.


Lists are defined by enclosing elements in square brackets [].
Elements in a list are separated by commas.
Example:
my_list = [1, 2, 3, "apple", "banana"]
Accessing List Elements
Elements in a list are accessed by their index.
Indexing starts at 0 for the first element.
Example:
first_element = my_list[0] # Accesses the first element (1)
Modifying Lists
Lists are mutable; you can change, add, or remove elements.
Example:
my_list[2] = 4 # Changes the third element to 4
List Length
You can find the number of elements in a list using len().
Example:
length = len(my_list) # Returns the length of the list (5)
Adding Elements
You can add elements to a list using append() or insert().
Example:
my_list.append("cherry") # Adds "cherry" to the end of the list
Removing Elements
Use remove() or pop() to remove elements from a list.
Example:
my_list.remove(2) # Removes the element with the value 2

Creating a List of the Top Five Cars (User Input)


Python code
# Create an empty list to store the cars
top_cars = []
# Get input from the user for the top five cars
for i in range(5):
car = input(f"Enter the {i + 1} car: ")
top_cars.append(car)
# Display the list of top cars
print("Top Five Cars:")
for car in top_cars:
print(car)

1. Create an Empty List top_cars:


top_cars = []
Here, we initialize an empty list called top_cars to store the top five cars provided by
the user.
2. Get Input from the User:
for i in range(5):
car = input(f"Enter the {i + 1} car: ")
top_cars.append(car)
o This code uses a for loop to iterate five times, once for each car.
o In each iteration, it uses the input() function to prompt the user to enter the
name of a car. f"Enter the {i + 1} car: " is used to display a user-
friendly prompt indicating which car they should enter (1st, 2nd, etc.).
o The entered car name is stored in the car variable.
o The append() method is used to add the entered car to the top_cars list.
3. Display the List of Top Cars:
print("Top Five Cars:")
for car in top_cars:
print(car)
o After the user has entered all five cars, this code first prints "Top Five Cars:" to
indicate what is being displayed.
o It then uses a for loop to iterate through the top_cars list and prints each car
name, one by one.
So, the code effectively collects the names of the top five cars from the user and stores them in a
list. Finally, it displays the list of those cars to the user.
For example, if the user enters "Toyota," "Honda," "Ford," "Chevrolet," and "BMW" as their top
five cars, the code will display:
Top Five Cars:
Toyota
Honda
Ford
Chevrolet
BMW

You might also like