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