</>
Skip to content
Python lessons (13/45)

Python — Lists

Creating lists

Lists are Python's most versatile collection — ordered, mutable, and允许 duplicates:

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

Accessing elements

Lists are zero-indexed:

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

print(fruits[0])   # apple
print(fruits[2])   # cherry
print(fruits[-1])  # cherry (last element)
print(fruits[-2])  # banana (second to last)

Slicing

Extract sublists with [start:stop:step]:

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

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

Slicing creates a new list — the original is unchanged.

Modifying lists

Lists are mutable — you can change, add, and remove elements:

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

# Change an element
fruits[1] = "blueberry"
print(fruits)  # ["apple", "blueberry", "cherry"]

# Change a slice
fruits[0:2] = ["grape", "kiwi"]
print(fruits)  # ["grape", "kiwi", "cherry"]

Adding elements

fruits = ["apple", "banana"]

# append — add to end
fruits.append("cherry")
print(fruits)  # ["apple", "banana", "cherry"]

# insert — add at specific position
fruits.insert(1, "blueberry")
print(fruits)  # ["apple", "blueberry", "banana", "cherry"]

# extend — add multiple items
fruits.extend(["grape", "kiwi"])
print(fruits)  # ["apple", "blueberry", "banana", "cherry", "grape", "kiwi"]

# concatenation — creates a new list
new = fruits + ["mango"]

Removing elements

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

# remove — first occurrence of value
fruits.remove("banana")
print(fruits)  # ["apple", "cherry", "banana"]

# pop — remove and return element at index
last = fruits.pop()
print(last)    # banana
print(fruits)  # ["apple", "cherry"]

# pop at index
first = fruits.pop(0)
print(first)   # apple

# del — remove by index or slice
numbers = [0, 1, 2, 3, 4]
del numbers[2]
print(numbers)  # [0, 1, 3, 4]

del numbers[1:3]
print(numbers)  # [0, 4]

# clear — empty the list
fruits.clear()
print(fruits)  # []

List operations

a = [1, 2, 3]
b = [4, 5, 6]

# Concatenation
print(a + b)       # [1, 2, 3, 4, 5, 6]

# Repetition
print(a * 3)       # [1, 2, 3, 1, 2, 3, 1, 2, 3]

# Length
print(len(a))      # 3

# Membership
print(2 in a)      # True
print(5 not in a)  # True

# Min, max, sum
numbers = [3, 1, 4, 1, 5, 9]
print(min(numbers))  # 1
print(max(numbers))  # 9
print(sum(numbers))  # 23

List methods

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

# Sort — modifies in place
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# Sort in reverse
numbers.sort(reverse=True)
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

# sorted() — returns a new sorted list
original = [3, 1, 4, 1, 5]
new_sorted = sorted(original)
print(original)    # [3, 1, 4, 1, 5] — unchanged
print(new_sorted)  # [1, 1, 3, 4, 5]

# reverse — reverses in place
numbers.reverse()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# count occurrences
print(numbers.count(1))  # 2

# find index
print(numbers.index(5))  # 4

# copy — shallow copy
copy = numbers.copy()

Iterating over lists

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

# Basic iteration
for fruit in fruits:
    print(fruit)

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

# With index using range
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

List comprehensions

A concise way to create lists:

# Traditional way
squares = []
for x in range(10):
    squares.append(x ** 2)

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

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

# With transformation
words = ["hello", "world"]
upper_words = [word.upper() for word in words]
print(upper_words)  # ["HELLO", "WORLD"]

Nested lists

Lists can contain other lists:

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

print(matrix[0][0])  # 1
print(matrix[1][2])  # 6

# Flatten a nested list
flat = [item for row in matrix for item in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Unpacking

numbers = [1, 2, 3, 4, 5]

# Unpack all
a, b, c, d, e = numbers
print(a, b, c)  # 1 2 3

# Unpack with star
first, *middle, last = numbers
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

Common patterns

# Check if list is empty
if not fruits:
    print("No fruits")

# Find duplicates
from collections import Counter
counts = Counter([1, 2, 2, 3, 3, 3])
duplicates = [item for item, count in counts.items() if count > 1]

# Remove duplicates (preserves order)
unique = list(dict.fromkeys([1, 2, 2, 3, 3, 3]))

Mini Practice

  1. Create a list of your five favorite movies and print each one
  2. Slice a list to get every other element
  3. Use a list comprehension to create a list of squares from 1 to 20
  4. Sort a list of names alphabetically and in reverse
  5. Flatten a nested list [[1,2], [3,4], [5,6]] into [1,2,3,4,5,6]

Next: tuples — immutable sequences →

Related Topics

Frequently Asked Questions about Lists

What is Lists in Python?

Lists is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Lists?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lists.

Why is Lists important in Python?

Lists is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.