Python Lists
A list is an ordered, mutable collection of items written with square brackets []. Lists can hold mixed data types.
Creating Lists
Lists can be created with literals or the list() constructor.
numbers = [1, 2, 3, 4, 5]
mixed = [10, "hello", 3.14, True]
empty = []
print(numbers[0])
print(mixed[-1])
Try it Yourself โ
List Methods
Common methods: append(), insert(), remove(), pop(), sort(), reverse().
nums = [3, 1, 4, 1, 5]
nums.append(9)
nums.sort()
nums.pop()
print(nums)
Try it Yourself โ
Slicing Lists
Use list[start:stop:step] to extract sublists.
letters = ["a", "b", "c", "d", "e"]
print(letters[1:4])
print(letters[::-1])
Try it Yourself โ
List Comprehension
A compact way to create lists by applying an expression to each item.
squares = [x ** 2 for x in range(1, 6)]
evens = [x for x in range(10) if x % 2 == 0]
print(squares)
print(evens)
Try it Yourself โ