Welcome to Day 21 of the 100 Days of Python series!
Today we’re diving into one of Python’s most useful and versatile data types — the list.
Lists are ordered, changeable, and allow duplicate values. They’re your go-to structure for storing collections like user names, scores, tasks, or pretty much anything.
📦 What You’ll Learn
- How to create a list
- How to access list elements
- How to modify items
- Common use cases and tips
Let’s get started! 🐍
🔹 1. Creating a List
Lists are created using square brackets []
.
# Empty list
empty = []
# List of strings
fruits = ["apple", "banana", "cherry"]
# Mixed data types
info = ["Alice", 30, True]
You can also create a list from a string or range:
list_from_str = list("hello") # ['h', 'e', 'l', 'l', 'o']
list_from_range = list(range(5)) # [0, 1, 2, 3, 4]
🔹 2. Accessing List Elements
Use indexing to access items. Indexes start at 0
.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
Access a Range of Items – Slicing
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['cherry', 'date']
🔹 3. Modifying List Items
Lists are mutable, meaning you can change their contents.
Replace an Item
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
Add Items
fruits.append("date") # Add to end
fruits.insert(1, "kiwi") # Insert at index 1
Remove Items
fruits.remove("banana") # Remove by value
fruits.pop() # Remove last item
del fruits[0] # Remove by index
Clear All Items
fruits.clear() # Now an empty list
🔹 4. Check Membership
if "apple" in fruits:
print("Yes, apple is in the list")
🔹 5. Get Length of a List
print(len(fruits)) # Number of items in the list
🔹 6. Nested Lists
Lists can contain other lists (2D or more):
matrix = [
[1, 2],
[3, 4]
]
print(matrix[1][0]) # 3
🔹 7. Loop Through a List
for fruit in fruits:
print(fruit)
Use enumerate()
to get index + value:
for index, fruit in enumerate(fruits):
print(index, fruit)
🔹 8. Copy a List
copy1 = fruits.copy()
copy2 = fruits[:] # Slice syntax
Avoid copy = fruits
– it just creates a reference.
💡 Pro Tip: Heterogeneous Lists Are Allowed
Lists can contain anything — even functions, objects, or other lists:
mixed = [42, "hello", [1, 2], True, len]
🧠 Recap
Today you learned:
- How to create and initialize lists
- How to access and slice items using indexing
- How to add, change, or remove items
- Tips on copying, looping, and nested lists
Top comments (0)