A List in Python is used to store multiple items in a single variable.
Lists are:
- Ordered
- Changeable (mutable)
- Allow duplicate values
1οΈβ£ Creating a List
numbers = [1, 2, 3, 4, 5]
print(numbers)
Output
[1, 2, 3, 4, 5]
Lists can store different data types.
data = [10, "Python", 3.5, True]
print(data)
2οΈβ£ Accessing List Elements
Lists use index numbers starting from 0.
fruits = ["apple", "banana", "cherry"]print(fruits[0])
print(fruits[1])
print(fruits[2])
Output
apple
banana
cherry
Negative indexing:
print(fruits[-1])
Output
cherry
3οΈβ£ Changing List Items
Lists are mutable, so values can be changed.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)
Output
['apple', 'orange', 'cherry']
4οΈβ£ List Length
Use len() to get number of items.
fruits = ["apple", "banana", "cherry"]
print(len(fruits))
Output
3
5οΈβ£ Adding Items to a List
append()
Adds item to the end
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
Output
['apple', 'banana', 'mango']
insert()
Adds item at a specific position
fruits = ["apple", "banana"]
fruits.insert(1, "orange")
print(fruits)
Output
['apple', 'orange', 'banana']
6οΈβ£ Removing Items
remove()
Removes a specific value
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
Output
['apple', 'cherry']
pop()
Removes item using index
fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)
Output
['apple', 'cherry']
7οΈβ£ Loop Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
8οΈβ£ List Slicing
Get a portion of a list.
numbers = [1,2,3,4,5]
print(numbers[1:4])
Output
[2, 3, 4]
9οΈβ£ Check if Item Exists
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, it exists")
Output
Yes, it exists
π Clear a List
fruits = ["apple", "banana"]
fruits.clear()
print(fruits)
Output
[]
β Example Program
fruits = ["apple", "banana", "cherry"]fruits.append("mango")
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
mango