Skip to content

Python Programming · Week 5

Lists

Step 1 of 6

In Python, a list is a versatile and powerful data structure that allows you to store multiple items in a single variable. Think of a list as a container that can hold various types of data, much like a shopping list can contain different items.

Lists are:

  • Ordered: Items have a defined order, and that order will not change.
  • Mutable: You can change, add, and remove items in a list after it is created.
  • Allow duplicates: Since lists are indexed, they can have items with the same value.

Example of a List:

my_list = [1, "apple", 3.14, True]

In this example, we've created a list called 'my_list' that contains four different types of data:

  • An integer (1)
  • A string ("apple")
  • A float (3.14)
  • A boolean (True)
This demonstrates how flexible lists can be in Python.

Real-world Analogy

Imagine a backpack. You can put different items in it: books, pens, a water bottle, and snacks. Each item can be different, just like in a Python list. You can add or remove items from your backpack as needed, similar to how you can modify a list.

Try it Yourself

Now, let's create three different lists and print them. Follow these steps:

  1. Create a list of fruits
  2. Create a list of numbers
  3. Create a mixed list with different types of data
  4. Print each list
Hint: To create a list, use square brackets [ ] and separate items with commas. To print a list, you can simply use the print() function with the list name as an argument.
Starter code
# Step 1: Create a list of fruits
fruits = ["apple", "banana", "orange"]

# Step 2: Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Step 3: Create a mixed list
mixed = [True, "Python", 3.14, [1, 2, 3]]

# Step 4: Print the lists
print("Fruits:", fruits)
print("Numbers:", numbers)
print("Mixed:", mixed)

Write your code here