~2 min read • Updated Jul 18, 2025
Defining Lists in Python
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"]
Key Characteristics of Lists
- Mutable: You can change, add, or remove items.
- Indexed and Sliced: Supports access by position and range.
- Mixed Types: Accepts strings, numbers, booleans, lists, and more.
- Nesting: Can contain other lists or iterable objects.
Accessing List Elements
my_list = [5, 10, 15, 20]
print(my_list[0]) # 5
print(my_list[-1]) # 20
print(my_list[1:3]) # [10, 15]
Common List Methods
| 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 |
Method Examples
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
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]
Conclusion
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.
Written & researched by Dr. Shahin Siami