Python Lists

Comprehensions, slicing, sorting, and friends for sequences.

  • list comprehension
  • python slice
  • sorted key
  • zip
  • any all

Python Lists

Comprehensions, slicing, sorting, and friends for sequences.

Commands

CommandWhat it does
[x*x for x in range(10)]List comprehension
nums[1:4]Slice (start inclusive, end exclusive)
sorted(users, key=lambda u: u.name)Sort without mutating
zip(names, scores)Pair two sequences
any(x > 0 for x in nums)Existence check, short-circuits

Example

scores = [("ada", 95), ("grace", 88)]
top = sorted(scores, key=lambda s: s[1], reverse=True)
print([name for name, _ in top])

FAQ

list vs tuple?

Lists mutate (append/sort); tuples are fixed and hashable — use tuples for dict keys and records.

Why is my default-arg list shared?

Mutable default args persist across calls; use None and build inside the function.

الأسئلة الشائعة

list vs tuple?
Lists mutate (append/sort); tuples are fixed and hashable — use tuples for dict keys and records.
Why is my default-arg list shared?
Mutable default args persist across calls; use None and build inside the function.

Python