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:
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)
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:
- Create a list of fruits
- Create a list of numbers
- Create a mixed list with different types of data
- Print each list
# 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)