Python Lists

"Lists in Python are ordered collections that can store multiple values in a single variable. They're one of the most versatile and commonly used data structures, allowing you to organize and manipulate groups of related data efficiently."- Gemini 2025

What is a List?

A list is an ordered collection of items that can hold multiple values of any type. Lists are:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True, 3.14]
empty = []

Creating Lists
Using Square Brackets

The most common way to create a list is with square brackets:

colors = ["red", "green", "blue"]
ages = [15, 16, 17, 18]
Using the list() Function

You can also create lists using the list() function:

letters = list("hello")      # ['h', 'e', 'l', 'l', 'o']
numbers = list(range(5))     # [0, 1, 2, 3, 4]

Accessing List Items
Indexing

Access individual items using their index (position). Python uses zero-based indexing, so the first item is at index 0.

fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0])    # Output: apple
print(fruits[2])    # Output: cherry
print(fruits[-1])   # Output: date (last item)
print(fruits[-2])   # Output: cherry (second from end)
Slicing

Extract a portion of a list using slicing with the syntax [start:end]. The end index is not included.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[2:5])     # Output: [2, 3, 4]
print(numbers[:3])      # Output: [0, 1, 2] (from start)
print(numbers[7:])      # Output: [7, 8, 9] (to end)
print(numbers[::2])     # Output: [0, 2, 4, 6, 8] (every 2nd item)
print(numbers[::-1])    # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reversed)

Modifying Lists
Changing Items

You can change list items by assigning new values to specific indices:

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)           # Output: ['apple', 'blueberry', 'cherry']
Adding Items
Method Description Example
append() Adds an item to the end fruits.append("date")
insert() Adds an item at a specific position fruits.insert(1, "banana")
extend() Adds multiple items from another list fruits.extend(["fig", "grape"])
Removing Items
Method Description Example
remove() Removes the first occurrence of a value fruits.remove("apple")
pop() Removes and returns item at index (default: last) last = fruits.pop()
clear() Removes all items fruits.clear()
del Deletes item(s) at specific index or slice del fruits[0]

Common List Operations
Operation Description Example
len() Returns the number of items len(fruits)
in Checks if item exists in list "apple" in fruits
+ Concatenates two lists [1, 2] + [3, 4]
* Repeats a list [1, 2] * 3
count() Counts occurrences of a value numbers.count(5)
index() Finds the index of first occurrence fruits.index("apple")
sort() Sorts the list in place numbers.sort()
reverse() Reverses the list in place fruits.reverse()

Looping Through Lists
For Loop

The most common way to iterate through a list:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
With Index

Use enumerate() to get both index and value:

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Creating and accessing lists

fruits = ["apple", "banana", "cherry"]
print(fruits[0])           # Output: apple
print(fruits[-1])          # Output: cherry


# Adding items

shopping_list = ["milk", "bread"]
shopping_list.append("eggs")
shopping_list.insert(0, "butter")
print(shopping_list)       # Output: ['butter', 'milk', 'bread', 'eggs']


# Removing items

colors = ["red", "green", "blue", "yellow"]
colors.remove("green")
last_color = colors.pop()
print(colors)              # Output: ['red', 'blue']
print(last_color)          # Output: yellow


# Slicing lists

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])        # Output: [2, 3, 4]
print(numbers[:3])         # Output: [0, 1, 2]
print(numbers[7:])         # Output: [7, 8, 9]


# List operations

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)            # Output: [1, 2, 3, 4, 5, 6]

repeated = [0] * 5
print(repeated)            # Output: [0, 0, 0, 0, 0]


# Checking membership

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)   # Output: True
print("grape" in fruits)   # Output: False


# Looping through lists

for fruit in fruits:
    print(f"I like {fruit}")


# List methods

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers))        # Output: 8
print(numbers.count(1))    # Output: 2
print(numbers.index(4))    # Output: 2

numbers.sort()
print(numbers)             # Output: [1, 1, 2, 3, 4, 5, 6, 9]


# Creating lists with range

evens = list(range(0, 10, 2))
print(evens)               # Output: [0, 2, 4, 6, 8]
# List comprehension - creating lists efficiently

squares = [x**2 for x in range(10)]
print(squares)             # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

evens = [x for x in range(20) if x % 2 == 0]
print(evens)               # Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


# Nested lists (2D lists)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][2])        # Output: 6 (row 1, column 2)


# Copying lists

original = [1, 2, 3]
shallow_copy = original.copy()
deep_copy = original[:]

original.append(4)
print(original)            # Output: [1, 2, 3, 4]
print(shallow_copy)        # Output: [1, 2, 3]


# Finding min, max, and sum

numbers = [45, 23, 67, 12, 89, 34]
print(min(numbers))        # Output: 12
print(max(numbers))        # Output: 89
print(sum(numbers))        # Output: 270


# Filtering lists

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)               # Output: [2, 4, 6, 8, 10]


# Sorting with key function

words = ["banana", "pie", "Washington", "book"]
words.sort(key=len)
print(words)               # Output: ['pie', 'book', 'banana', 'Washington']

words.sort(key=str.lower)
print(words)               # Output: ['banana', 'book', 'pie', 'Washington']


# Enumerate with custom start

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")


# Zip - combining lists

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")


# Unpacking lists

first, second, *rest = [1, 2, 3, 4, 5]
print(first)               # Output: 1
print(second)              # Output: 2
print(rest)                # Output: [3, 4, 5]


# List of lists - practical example

students = [
    ["Alice", 85, 92, 78],
    ["Bob", 79, 95, 88],
    ["Charlie", 92, 88, 84]
]

for student in students:
    name = student[0]
    average = sum(student[1:]) / len(student[1:])
    print(f"{name}'s average: {average:.1f}")


# Removing duplicates while preserving order

numbers = [1, 2, 2, 3, 4, 3, 5, 1]
unique = []
for num in numbers:
    if num not in unique:
        unique.append(num)
print(unique)              # Output: [1, 2, 3, 4, 5]


# Common pattern: accumulating results

numbers = [1, 2, 3, 4, 5]
doubled = []
for num in numbers:
    doubled.append(num * 2)
print(doubled)             # Output: [2, 4, 6, 8, 10]
Test at OneCompiler
Practice in W3Schools!