Lists are Python's workhorse collection; nearly every program uses them.
A list is an ordered, mutable sequence written with square brackets: nums = [3, 1, 4]. It can hold any mix of objects, though in practice lists usually hold items of one kind.
Indexing starts at 0, and negative indexes count from the end: nums[0] is the first item, nums[-1] the last. Indexing past the end raises IndexError. len(nums) gives the length and x in nums tests membership (a linear scan).
Lists change in place:
append(x)adds to the end;extend(other)adds every item of another iterableinsert(i, x)inserts before indexi;nums[i] = xreplacespop()removes and returns the last item (pop(i)a specific one);remove(x)deletes the first equal valuesort()sorts in place,reverse()reverses in place
These in-place methods return None. If you want a new sorted list and to keep the original, use the built-in sorted(nums). Both accept reverse=True and a key function, e.g. sorted(words, key=len).
Performance matters once lists get large: appending and popping at the end are fast (amortised O(1)), but insert(0, x), pop(0) and x in nums are O(n). For queues use collections.deque; for fast membership tests use a set.
+ concatenates two lists into a new one, and [0] * 5 makes [0, 0, 0, 0, 0].
Example
nums = [3, 1, 4]
nums.append(1)
nums.extend([5, 9])
print(nums) # [3, 1, 4, 1, 5, 9]
print(nums[0], nums[-1], len(nums)) # 3 9 6
last = nums.pop()
print(last, nums) # 9 [3, 1, 4, 1, 5]
print(sorted(nums)) # [1, 1, 3, 4, 5] (new list)
print(nums) # [3, 1, 4, 1, 5] (unchanged)
nums.sort(reverse=True)
print(nums) # [5, 4, 3, 1, 1]
words = ["kiwi", "fig", "banana"]
print(sorted(words, key=len)) # ['fig', 'kiwi', 'banana']
print(nums.sort()) # None -- sort() works in placeRemember
- Lists are ordered and mutable; index from 0, or from the end with -1
list.sort()sorts in place and returns None;sorted()returns a new list- Appending/popping at the end is fast; at the front it is O(n)
Watch out for
- Writing
nums = nums.sort(), which setsnumsto None.