Lists are defined using square brackets []
and can contain any combination of data types:
my_list = [10, "Ali", True, 3.14]
empty_list = []
nested_list = [1, [2, 3], "hello"]
my_list = [5, 10, 15, 20]
print(my_list[0]) # 5
print(my_list[-1]) # 20
print(my_list[1:3]) # [10, 15]
Method | Description |
---|---|
append(x) | Adds x to the end of the list |
insert(i, x) | Adds x at index i |
remove(x) | Removes first occurrence of x |
pop(i) | Removes and returns item at index i |
index(x) | Returns first index of x |
count(x) | Counts how many times x appears |
sort() | Sorts list in ascending order |
reverse() | Reverses the list order |
copy() | Returns a shallow copy of the list |
clear() | Removes all items from the list |
numbers = [3, 6, 1]
numbers.append(9) # [3, 6, 1, 9]
numbers.insert(1, 4) # [3, 4, 6, 1, 9]
numbers.remove(6) # [3, 4, 1, 9]
print(numbers.pop()) # 9
print(numbers.index(4)) # 1
print(numbers.count(1)) # 1
numbers.sort() # [1, 3, 4]
numbers.reverse() # [4, 3, 1]
List comprehension offers a compact way to build lists using filters or transformations.
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Lists in Python are fundamental tools for organizing and manipulating collections of data. With flexible size, versatile methods, and readable syntax, they are crucial for everything from user input handling to algorithm development and data analysis.