Lists in Python
A list is a collection of items stored in a single variable. Lists are ordered, mutable, and allow duplicate values.
💡 Lists are created using square brackets [ ].
Creating a List
numbers = [1, 2, 3, 4, 5]
names = ["Khushi", "Python", "Learner"]
mixed = [10, "Hello", True]
print(numbers)
print(names)
print(mixed)
Accessing List Elements
List elements are accessed using index numbers (starting from 0).
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[1])
print(fruits[-1])
Modifying Lists
Lists are mutable, meaning you can change their values.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)
Common List Methods
numbers = [1, 2, 3]
numbers.append(4)
numbers.insert(1, 10)
numbers.remove(2)
numbers.pop()
print(numbers)
Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Common Mistakes
❌ Accessing index that doesn’t exist
❌ Forgetting list indices start from 0
❌ Confusing append() with insert()
❌ Forgetting list indices start from 0
❌ Confusing append() with insert()
Practice Exercises
- Create a list of 5 numbers
- Print the first and last elements
- Add a new number and remove one