Python Lists: From the Basics to Everyday Idioms (append, slicing, sort, comprehensions)

A Python list is an ordered, mutable collection: it keeps items in the order you put them, lets you change them in place, and can hold any mix of types. This guide covers what you need day to day, from creating and slicing lists to sorting, comprehensions and the copying mistakes that catch almost everyone once. Each topic links to a more detailed article as the series grows.
All examples were run on Python 3.13; list behaviour shown here has been stable throughout Python 3.
Creating a list
Write the items between square brackets, separated by commas. A list can hold strings, numbers, None or other lists, and len() returns the number of items.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, None, [5, 6]]
print(len(fruits), fruits[0], fruits[-1])
print(list("abc"), list(range(5)))
3 apple cherry
['a', 'b', 'c'] [0, 1, 2, 3, 4]
The list() constructor turns any iterable into a list: a string becomes a list of characters, a range a list of integers. To turn a sentence into words instead, see splitting a string into a list.
Indexing and slicing
Indexes start at 0; negative indexes count from the end, so -1 is the last item. A slice [start:stop:step] returns a new list from start up to, but not including, stop.
nums = [10, 20, 30, 40, 50]
print(nums[1:3], nums[:2], nums[-2:], nums[::2], nums[::-1])
[20, 30] [10, 20] [40, 50] [10, 30, 50] [50, 40, 30, 20, 10]
Reading an index that does not exist raises IndexError, but a slice never does: nums[10:20] simply returns an empty list. nums[::-1] is the quickest way to get a reversed copy.
Adding items: append, extend, insert
nums.append(60) # one item at the end
nums.extend([70, 80]) # every item of another iterable
nums.insert(0, 0) # one item at a given position
print(nums)
[0, 10, 20, 30, 40, 50, 60, 70, 80]
The difference between append and extend is the classic trap: nums.append([70, 80]) would add a single item, the list [70, 80], nested inside nums. insert shifts every following item, so on long lists it is slower than appending at the end.
Removing items: pop, remove, del, clear
print(nums.pop(), nums.pop(0), nums)
nums.remove(30) # first item equal to 30
del nums[1:3] # a slice
print(nums)
80 0 [10, 20, 30, 40, 50, 60, 70]
[10, 50, 60, 70]
pop() removes and returns the last item, or the item at the index you pass; on an empty list it raises IndexError. remove(x) deletes the first item equal to x and raises ValueError if there is none. del works with indexes and slices, and clear() empties the list.
Sorting and reversing
list.sort() sorts in place and returns None; the built-in sorted() returns a new list and works on any iterable. Both accept reverse=True and a key function.
letters = ["c", "a", "b"]
letters.sort()
print(letters)
print(sorted([3, 1, 2], reverse=True))
words = ["pear", "Fig", "apple"]
print(sorted(words, key=str.lower))
['a', 'b', 'c']
[3, 2, 1]
['apple', 'Fig', 'pear']
Writing letters = letters.sort() is a frequent bug: it replaces your list with None. Python's sort is stable, so items that compare equal keep their original order, which the Sorting Techniques guide in the official documentation uses to sort by several keys in turn.
Searching: in, index, count
print([3, 1, 2].index(1), [1, 2, 2, 3].count(2), 2 in [1, 2, 3])
1 2 True
The in operator is the readable way to test membership. On a long list it checks items one by one; if you test membership many times, convert the data to a set first. Counting how often each value appears is covered in counting word occurrences in a list.
List comprehensions
A comprehension builds a list from an iterable in one expression, optionally with a filter. It replaces most loops that only append to a list.
squares = [n * n for n in range(6)]
evens = [n for n in range(10) if n % 2 == 0]
print(squares, evens)
[0, 1, 4, 9, 16, 25] [0, 2, 4, 6, 8]
Keep comprehensions short. Once you need several conditions or nested loops, a regular for loop is easier to read and debug.
Copying a list without surprises
Assignment never copies a list: it gives the same list a second name.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # a changed too
c = a.copy()
c.append(5)
print(a, c)
[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 5]
a.copy(), a[:] and list(a) all make a shallow copy: the outer list is new, but nested lists inside it are shared. The same rule explains the most famous list bug, building a grid with multiplication:
grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0]]
The first version repeats one inner list twice; the comprehension creates a new inner list for each row. Our article on two-dimensional arrays in Python goes further, and the standard library's copy.deepcopy() copies nested structures completely.
Everyday idioms
for i, f in enumerate(fruits, start=1):
print(i, f)
for f, p in zip(fruits, [1.2, 0.5, 3.0]):
print(f, p)
first, *rest = [1, 2, 3, 4]
print(first, rest)
print(sum([1, 2, 3]), max([4, 9, 2]), min([4, 9, 2]))
print(", ".join(fruits))
1 apple
2 banana
3 cherry
apple 1.2
banana 0.5
cherry 3.0
1 [2, 3, 4]
6 9 2
apple, banana, cherry
enumerate()gives you the position and the item, instead of looping overrange(len(...)).zip()walks several lists in parallel and stops at the shortest.- Star unpacking (
first, *rest) splits a list into its head and the remainder. ", ".join()turns a list of strings back into a single string; every item must already be a string.
Lists, tuples, sets or arrays?
Use a list for an ordered collection that changes. Use a tuple for a fixed record that should not change, a set when you only care about membership and uniqueness, and a dictionary when you look items up by a key. For large amounts of numbers, NumPy arrays and pandas columns are far faster than lists, because they store values in compact typed blocks. The official Python tutorial on data structures compares these types in more detail.
Summary
Create lists with brackets or list(), read them with indexes and slices, grow them with append, extend and insert, shrink them with pop, remove and del, and sort with sort() or sorted(). Build new lists with comprehensions, and remember that assignment shares a list while copy() duplicates only its outer layer.
Sources
- Python Software Foundation, The Python Tutorial: Data Structures.
- Python Software Foundation, Built-in Types: Sequence Types, list, tuple, range.
- Python Software Foundation, Sorting Techniques.
PythonSplit a string into a list
Split strings into lists in Python: str.split with and without sep, maxsplit, rsplit, splitlines, re.split for multiple delimiters, list(), csv and shlex.
PythonCount word occurrences
Count how often words appear in a Python list with list.count, collections.Counter, dict and defaultdict loops, normalization of case and punctuation, and pandas.
PythonTwo-dimensional arrays
Create 2D arrays in Python with nested list comprehensions or NumPy, avoid the [[0]*n]*m aliasing bug, and index, iterate, transpose and slice correctly.