Lists#

A list is the most commonly used data structure in Python. It stores ordered, duplicate-allowed, mutable elements, and elements do not need to be the same type:

1
2
3
4
5
# Create a list
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]  # Mixed types are allowed
empty = []  # Empty list

Accessing Elements#

Index#

Indexes start at 0; negative indexes count from the end:

1
2
3
4
5
6
7
8
fruits = ["apple", "banana", "cherry", "date"]
#          0         1         2         3
#         -4        -3        -2        -1

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

Slicing#

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

print(nums[2:5])    # [2, 3, 4]
print(nums[:4])     # [0, 1, 2, 3]
print(nums[6:])     # [6, 7, 8, 9]
print(nums[::2])    # [0, 2, 4, 6, 8] (every other element)
print(nums[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse)

Modifying Lists#

Modify elements#

1
2
3
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)  # ['apple', 'mango', 'cherry']

Add elements#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
fruits = ["apple", "banana"]

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

# insert(): insert at position
fruits.insert(1, "mango")
print(fruits)  # ['apple', 'mango', 'banana', 'cherry']

# extend(): merge another list
more = ["date", "elderberry"]
fruits.extend(more)
print(fruits)  # ['apple', 'mango', 'banana', 'cherry', 'date', 'elderberry']

# Or use + concatenation (creates a new list)
new_list = fruits + ["fig"]

Delete elements#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fruits = ["apple", "banana", "cherry", "banana"]

# remove(): remove first matching value
fruits.remove("banana")
print(fruits)  # ['apple', 'cherry', 'banana']

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

# pop(index): remove at specific index
item = fruits.pop(0)
print(item)    # apple

# del: delete by index or slice
nums = [1, 2, 3, 4, 5]
del nums[2]
print(nums)  # [1, 2, 4, 5]

del nums[1:3]
print(nums)  # [1, 5]

# clear(): clear the list
nums.clear()
print(nums)  # []

Query Operations#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fruits = ["apple", "banana", "cherry", "banana"]

# Check existence
print("banana" in fruits)     # True
print("mango" not in fruits)  # True

# Count
print(fruits.count("banana"))  # 2

# Find index (first match)
print(fruits.index("cherry"))  # 2

# Length
print(len(fruits))  # 4

Sorting#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

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

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

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

# Custom sort key
words = ["banana", "apple", "cherry", "kiwi"]
words.sort(key=len)           # Sort by length
print(words)  # ['kiwi', 'apple', 'banana', 'cherry']

words.sort(key=lambda w: w[-1])  # Sort by last letter

Reverse#

1
2
3
4
5
6
7
nums = [1, 2, 3, 4, 5]

nums.reverse()
print(nums)  # [5, 4, 3, 2, 1]

# Can also use slicing (creates new list)
reversed_nums = nums[::-1]

Copying Lists#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
a = [1, 2, 3]

# Direct assignment: both variables point to same object
b = a
b.append(4)
print(a)  # [1, 2, 3, 4] (a is also modified!)

# Shallow copy: creates new object
c = a.copy()        # Method 1
d = list(a)         # Method 2
e = a[:]            # Method 3

c.append(5)
print(a)  # [1, 2, 3, 4] (a is not affected)
print(c)  # [1, 2, 3, 4, 5]

List Comprehension#

List comprehension is a concise Python syntax for building a new list in one line, replacing the typical for loop + append pattern.

Basic syntax:

[expression for variable in iterable]
[expression for variable in iterable if condition]

Basic form: transform every element#

Traditional for loop:

1
2
3
4
squares = []
for x in range(1, 6):
    squares.append(x ** 2)
print(squares)  # [1, 4, 9, 16, 25]

Rewritten as a list comprehension:

1
2
squares = [x ** 2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

With condition: filter elements#

Add if condition at the end to keep only matching elements:

1
2
3
4
5
6
7
# Keep only even numbers
even = [x for x in range(10) if x % 2 == 0]
print(even)  # [0, 2, 4, 6, 8]

# Squares of numbers greater than 3
big_squares = [x ** 2 for x in range(1, 8) if x > 3]
print(big_squares)  # [16, 25, 36, 49]

if-else: choose a different output per element#

Put if-else before the for (in the expression position) to transform every element — nothing is filtered out:

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

# if at the end → filter (keep only evens)
keep_even = [x for x in nums if x % 2 == 0]
print(keep_even)   # [2, 4, 6]

# if-else at the front → transform (every element is kept; odds become 0)
mark_even = [x if x % 2 == 0 else 0 for x in nums]
print(mark_even)   # [0, 2, 0, 4, 0, 6]

Nested comprehension: flatten a 2-D list#

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

# Equivalent to two nested for loops: outer over rows, inner over elements
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Common Built-in Functions#

sum() / max() / min() / len()#

The four most-used functions for working with numeric lists:

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

print(sum(nums))    # 31  → add all elements
print(max(nums))    # 9   → largest value
print(min(nums))    # 1   → smallest value
print(len(nums))    # 8   → number of elements

sum() accepts an optional starting value (default 0):

1
print(sum(nums, 100))   # 131 (starts accumulating from 100)

max() and min() accept a key function to control how elements are compared:

1
2
3
4
5
words = ["banana", "apple", "kiwi", "cherry"]

print(max(words))              # kiwi   (default: alphabetical)
print(max(words, key=len))     # banana (longest word)
print(min(words, key=len))     # kiwi   (shortest word)

sorted() / reversed()#

sorted() returns a new list and leaves the original unchanged. reversed() returns a reverse iterator — wrap it with list() to get a list:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
nums = [3, 1, 4, 1, 5]

new = sorted(nums)               # ascending, new list
print(nums)   # [3, 1, 4, 1, 5] (original unchanged)
print(new)    # [1, 1, 3, 4, 5]

desc = sorted(nums, reverse=True)
print(desc)   # [5, 4, 3, 1, 1]

rev = list(reversed(nums))
print(rev)    # [5, 1, 4, 1, 3]

enumerate() / zip()#

enumerate() yields both the index and the value; zip() pairs up elements from multiple lists:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
fruits = ["apple", "banana", "cherry"]

# enumerate: useful when you need a numbered loop
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry

# zip: combine two lists element by element
prices = [30, 15, 25]
for fruit, price in zip(fruits, prices):
    print(f"{fruit}: ${price}")
# apple: $30
# banana: $15
# cherry: $25

zip() stops at the shorter list — extra elements are discarded:

1
2
3
a = [1, 2, 3, 4]
b = ["x", "y"]
print(list(zip(a, b)))   # [(1, 'x'), (2, 'y')]

any() / all()#

any() returns True if at least one element satisfies the condition; all() requires every element to satisfy it:

1
2
3
4
5
scores = [85, 92, 78, 60, 95]

print(any(s >= 90 for s in scores))   # True  (92 and 95 qualify)
print(all(s >= 60 for s in scores))   # True  (all pass)
print(all(s >= 80 for s in scores))   # False (60 and 78 do not)

list() conversion#

list() converts any iterable into a list:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# string → list
chars = list("Python")
print(chars)   # ['P', 'y', 't', 'h', 'o', 'n']

# range → list
r = list(range(5))
print(r)       # [0, 1, 2, 3, 4]

# tuple → list
t = list((1, 2, 3))
print(t)       # [1, 2, 3]

Practical Examples#

Remove duplicate elements#

1
2
3
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(sorted(unique))  # [1, 2, 3, 4]

Flatten nested list#

1
2
3
nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for sublist in nested for x in sublist]
print(flat)  # [1, 2, 3, 4, 5, 6]

Split into two groups by condition#

1
2
3
4
5
numbers = range(1, 11)
even = [n for n in numbers if n % 2 == 0]
odd = [n for n in numbers if n % 2 != 0]
print(even)  # [2, 4, 6, 8, 10]
print(odd)   # [1, 3, 5, 7, 9]