Python Lists
Ordered, mutable, allows duplicates — the most-used collection in Python.
Creating lists
Python
fruits = ["apple", "banana", "cherry"]
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, None, 3.14]
empty = []
nested = [[1,2], [3,4], [5,6]]
Indexing and slicing
Python
fruits = ["apple", "banana", "cherry", "date"]
fruits[0] # "apple" — first
fruits[-1] # "date" — last
fruits[1:3] # ["banana", "cherry"]
fruits[::2] # ["apple", "cherry"] — every 2nd
fruits[::-1] # reversed list
Modifying lists
Python
fruits = ["apple", "banana"]
fruits.append("cherry") # add to end: ["apple","banana","cherry"]
fruits.insert(1, "avocado") # insert at index: ["apple","avocado",...]
fruits.extend(["date", "fig"]) # add multiple items
fruits.remove("banana") # remove first occurrence
fruits.pop() # remove and return last item
fruits.pop(0) # remove and return item at index 0
fruits[0] = "APPLE" # update in place
fruits.clear() # remove all items
Sorting
Python
nums = [3, 1, 4, 1, 5, 9]
nums.sort() # sort in place: [1,1,3,4,5,9]
nums.sort(reverse=True) # descending: [9,5,4,3,1,1]
words = ["banana", "apple", "Cherry"]
words.sort(key=str.lower) # case-insensitive sort
sorted(nums) # returns NEW sorted list, doesn't change nums
List comprehensions
The Pythonic way to build a list from an iterable:
Python
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
upper_fruits = [f.upper() for f in ["apple", "banana"]]
# ["APPLE", "BANANA"]
Useful list operations
Python
len([1,2,3]) # 3
2 in [1,2,3] # True
[1,2] + [3,4] # [1,2,3,4] — concatenate
[0] * 5 # [0,0,0,0,0] — repeat
[1,2,3].count(2) # 1
[1,2,3].index(2) # 1
max([3,1,4,1,5]) # 5
sum([1,2,3,4]) # 10