PY

Lists

Python · 9 entries

Creating Lists

syntax
items = [val1, val2, ...]
items = list(iterable)
example
colors = ["red", "green", "blue"]
numbers = list(range(1, 6))
mixed = [1, "two", 3.0, True]
empty = []
print(numbers)
output
[1, 2, 3, 4, 5]

Note Lists can hold any mix of types. Use list() to convert other iterables (tuples, sets, generators) into lists.

Indexing & Negative Indexing

syntax
items[index]
items[-index]
example
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])
print(fruits[-1])
print(fruits[-2])
output
apple
date
cherry

Note Index 0 is the first element, -1 is the last. Accessing an index beyond the list length raises IndexError.

List Slicing

syntax
items[start:stop:step]
example
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[::2])
print(nums[::-1])
nums[1:3] = [200, 300]
print(nums)
output
[20, 30, 40]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
[10, 200, 300, 40, 50, 60]

Note Slice assignment can replace a range of elements. The replacement does not need to be the same length as the slice being replaced.

append, extend, insert

syntax
list.append(item)
list.extend(iterable)
list.insert(index, item)
example
tasks = ["email"]
tasks.append("report")
tasks.insert(0, "standup")
tasks.extend(["review", "deploy"])
print(tasks)
output
['standup', 'email', 'report', 'review', 'deploy']

Note append adds one item; extend adds each element from an iterable. Using append with a list nests it: [1].append([2,3]) gives [1, [2,3]].

remove, pop, del, clear

syntax
list.remove(value)
list.pop(index)
del list[index]
example
items = ["a", "b", "c", "d", "e"]
items.remove("c")
print(items)
last = items.pop()
print(last, items)
del items[0]
print(items)
output
['a', 'b', 'd', 'e']
e ['a', 'b', 'd']
['b', 'd']

Note remove() deletes the first matching value (raises ValueError if missing). pop() removes by index and returns the value. del removes by index without returning.

Sorting & Reversing

syntax
list.sort(key=None, reverse=False)
sorted(iterable, key=None, reverse=False)
example
prices = [29.99, 5.50, 12.00, 89.99]
prices.sort()
print(prices)

names = ["Charlie", "alice", "Bob"]
ordered = sorted(names, key=str.lower)
print(ordered)
output
[5.5, 12.0, 29.99, 89.99]
['alice', 'Bob', 'Charlie']

Note .sort() modifies the list in place and returns None. sorted() returns a new list. Use key= for custom ordering logic.

List Comprehensions

syntax
[expression for item in iterable if condition]
example
prices = [10, 25, 50, 75, 100]
affordable = [p for p in prices if p <= 50]
print(affordable)

squares = [n ** 2 for n in range(1, 6)]
print(squares)
output
[10, 25, 50]
[1, 4, 9, 16, 25]

Note Comprehensions are more Pythonic and faster than equivalent for-loop-with-append patterns. Keep them simple; if nesting gets deep, use a regular loop.

List Unpacking & Starred Expressions

syntax
a, b, *rest = some_list
example
coords = [10, 20, 30, 40, 50]
x, y, *remaining = coords
print(x, y, remaining)

first, *_, last = coords
print(first, last)
output
10 20 [30, 40, 50]
10 50

Note Use _ as a throwaway variable name for values you do not need. The starred variable always produces a list, even if empty.

Useful List Operations

syntax
len() / in / enumerate() / zip()
example
items = ["pen", "notebook", "eraser"]
print(len(items))
print("pen" in items)

for idx, item in enumerate(items, start=1):
    print(f"{idx}. {item}")
output
3
True
1. pen
2. notebook
3. eraser

Note enumerate() gives (index, value) pairs. Pass start= to begin counting from a number other than 0.