Guide Python Beginner

10.6 List Operators

Concatenation and repetition build brand-new lists, membership testing is a linear scan, and comparison works element-by-element and lexicographically -- the same rule used for tuple comparison.

2 min read

+ (Concatenation)

Concatenates two lists into a brand-new list — neither original list is modified.

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]

* (Repetition)

Repeats a list’s elements a given number of times.

>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]

in / not in

Tests membership — O(n) on a list, since it’s a linear scan (see 10.13 Performance), so convert to a set for repeated checks on large collections.

>>> 2 in [1, 2, 3]
True
>>> 5 not in [1, 2, 3]
True

Comparison

Lists compare element-by-element, lexicographically — the same rule used for tuple and string comparison (see 9.5 String Operators).

>>> [1, 2] == [1, 2]
True
>>> [1, 2] < [1, 3]     # first elements equal, second decides
True

Quick Interview Answer

+ and * both build a brand-new list rather than mutating either operand — + concatenates, * repeats. in/not in are O(n) linear scans, which matters if membership is being checked repeatedly on a large list; converting to a set first turns that into O(1) average-case lookups. Comparison operators compare element-by-element in order, exactly like lexicographic string comparison — the first differing pair of elements decides the result.”

Common Mistakes

  • Using [[0] * 3] * 3 to build a matrix — * repeats references to the same inner list, so mutating one “row” mutates all of them; a comprehension (see 10.9 Traversing and List Comprehensions) avoids this.
  • Repeatedly checking x in large_list inside a hot loop instead of converting to a set once beforehand, turning an O(n) scan into an O(1) lookup per check.
  • Comparing lists of different lengths and being surprised by the result — [1, 2] < [1, 2, 3] is True because the shorter list is treated as “less than” once it runs out of elements to compare, the same rule as string comparison.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form