🐍
Lists: Working with Collections
Beginner
90 XP
40 min
Lesson Content
Lists: Storing Multiple Items
Lists are ordered collections of items. They're one of Python's most versatile data structures, allowing you to store and manipulate multiple values.
Creating Lists
Lists are created using square brackets:
# Empty list
my_list = []
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "orange"]
# Mixed types
mixed = [1, "hello", 3.14, True]Accessing List Items
Use index numbers (starting from 0):
fruits = ["apple", "banana", "orange"]
# Access by index
print(fruits[0]) # apple (first item)
print(fruits[1]) # banana (second item)
print(fruits[-1]) # orange (last item, -1 is last)
# Negative indexing (from the end)
print(fruits[-2]) # banana (second from last)Modifying Lists
Lists are mutable (can be changed):
fruits = ["apple", "banana", "orange"]
# Change an item
fruits[0] = "grape" # ["grape", "banana", "orange"]
# Add items
fruits.append("mango") # Add to end
fruits.insert(1, "kiwi") # Insert at index 1
# Remove items
fruits.remove("banana") # Remove by value
fruits.pop() # Remove last item
fruits.pop(0) # Remove item at index 0List Slicing
Get a portion of a list:
numbers = [0, 1, 2, 3, 4, 5]
# Slice from index 1 to 4 (exclusive)
print(numbers[1:4]) # [1, 2, 3]
# Slice from start to index 3
print(numbers[:3]) # [0, 1, 2]
# Slice from index 2 to end
print(numbers[2:]) # [2, 3, 4, 5]
# Slice with step
print(numbers[::2]) # [0, 2, 4] (every 2nd item)List Methods
Common list operations:
numbers = [3, 1, 4, 1, 5]
# Get length
print(len(numbers)) # 5
# Count occurrences
print(numbers.count(1)) # 2
# Find index
print(numbers.index(4)) # 2
# Sort (modifies original)
numbers.sort() # [1, 1, 3, 4, 5]
# Reverse
numbers.reverse() # [5, 4, 3, 1, 1]
# Create sorted copy
sorted_nums = sorted(numbers)Looping Through Lists
fruits = ["apple", "banana", "orange"]
# Loop through items
for fruit in fruits:
print(fruit)
# Loop with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")List Comprehensions
Create lists concisely:
# Create list of squares
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]Example Code
Create and manipulate a list of student names.
# Create a list of student names
students = ["Alice", "Bob", "Charlie"]
# Add two more students
students.append("Diana")
students.append("Eve")
# Print all students
for student in students:
print(student)
# Print the number of students
print(f"Total students: {len(students)}")Expected Output:
Alice Bob Charlie Diana Eve Total students: 5
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code