Python Lists

What is a Python List?

A list is a built-in Python data structure used to store multiple items in a single variable.

 In Python, a list is created using square brackets [], and the items are separated by commas.

Example:

fruits = ["apple", "banana", "cherry"]
print(fruits)

✅ Output:

['apple', 'banana', 'cherry']

List Allows Duplicates

fruits = ["apple", "banana", "cherry", "apple"]
print(fruits)

Output:

['apple', 'banana', 'cherry', 'apple']

List Length

fruits = ["apple", "banana", "cherry"]
print(len(fruits))

Output:

3

List Can Contain Different Data Types

list1 = ["apple", 10, True, 5.5]
print(list1)

Output:

['apple', 10, True, 5.5]

Access List Items

fruits = ["apple", "banana", "cherry"]
print(fruits[1])
print(fruits[-1])

Output:

banana
cherry

Range of Indexes

fruits = ["apple", "banana", "cherry", "orange", "kiwi"]
print(fruits[1:4])

Output:

['banana', 'cherry', 'orange']

Change List Items

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)

Output:

['apple', 'mango', 'cherry']

Add Items to List

append() Example:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

Output:

['apple', 'banana', 'cherry', 'orange']

insert() Example:

fruits.insert(1, "grape")
print(fruits)

Output:

['apple', 'grape', 'banana', 'cherry', 'orange']

 Remove Items from List

remove():

fruits.remove("banana")
print(fruits)

Output:

['apple', 'grape', 'cherry', 'orange']

pop():

['apple', 'grape', 'cherry', 'orange']

Output:

['apple', 'grape', 'orange']

del:

del fruits[0]
print(fruits)

Output:

['grape', 'orange']

Clear List

fruits.clear()
print(fruits)

Output:

[]

Loop Through a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
   print(fruit)

Output:

apple
banana
cherry

Check if Item Exists

if "apple" in fruits:
   print("Yes, apple is in the list")

Output:

Yes, apple is in the list

Join Two Lists

Using +:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

Output:

['a', 'b', 'c', 1, 2, 3]

Using extend():

list1.extend(list2)
print(list1)

Output:

['a', 'b', 'c', 1, 2, 3]

List Comprehension

squares = [x**2 for x in range(6)]
print(squares)

Output:

[0, 1, 4, 9, 16, 25]

List Methods Summary

numbers = [5, 2, 9, 1]
numbers.sort()
print("Sorted:", numbers)
numbers.reverse()
print("Reversed:", numbers)
numbers.append(10)
print("Appended:", numbers)
numbers.pop()
print("Popped:", numbers)

Output:

Sorted: [1, 2, 5, 9]
Reversed: [9, 5, 2, 1]
Appended: [9, 5, 2, 1, 10]
Popped: [9, 5, 2, 1]

Summary

  • Python lists are created using square brackets: []
  • Lists are ordered, mutable, and allow duplicate values.
  • They support many methods: append(), remove(), sort(), extend(), etc.
  • Lists are essential for storing multiple items in one variable.