Lists are ordered, mutable collections defined with []. They hold elements of different types.
Methods
append(),insert(),remove(),pop(),sort()
List Comprehension
[x**2 for x in range(10) if x % 2 == 0]
Lists are ordered, mutable collections defined with []. They hold elements of different types.
append(), insert(), remove(), pop(), sort()[x**2 for x in range(10) if x % 2 == 0]
fruits = ["apple", "banana", "cherry"] fruits.append("date") print(fruits[0:2]) squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0]
fruits = ["apple", "banana", "cherry"] print("First:", fruits[0]) print("Last:", fruits[-1]) fruits.append("date") print("Append:", fruits) # Slicing print("Slice:", fruits[1:3]) # Methods fruits.sort() print("Sorted:", fruits) print("Count:", fruits.count("apple")) print("Index:", fruits.index("banana")) # Iteration for fruit in fruits: print("Fruit:", fruit) # List comprehension squares = [x * x for x in range(1, 6)] print("Squares:", squares)
Remove duplicates from a list preserving order.
seen = set()
result = []
for x in [1,2,2,3]:
if x not in seen:
seen.add(x)
result.append(x)
What does [1,2,3][1:3] return?
Slicing [1:3] returns elements at index 1 and 2.
Tuples for immutable data (dict keys, function returns). Lists for mutable collections.