It sounds like you're referring to common mistakes or inefficient practices when using Python lists. Here are some things to avoid:
π« 1. Using a List When a Set or Dict is Better
my_list = [1, 2, 3, 4, 5]
if 3 in my_list: # O(n) lookup time
print("Found!")
✅ Use a set for fast lookups (O(1)):
my_set = {1, 2, 3, 4, 5}
if 3 in my_set:
print("Found!")
π« 2. Using a List for Queue Operations (Use collections.deque
)
my_list = [1, 2, 3, 4, 5]
my_list.pop(0) # O(n) operation (slow!)
✅ Use deque
for O(1) pops:
from collections import deque
my_deque = deque([1, 2, 3, 4, 5])
my_deque.popleft() # O(1)
π« 3. Inefficient List Comprehension Inside a Loop
for i in range(10):
new_list = [x**2 for x in range(1000)] # Re-creating every loop iteration!
✅ Move it outside if it doesn’t change:
new_list = [x**2 for x in range(1000)]
for i in range(10):
# Use the precomputed list
pass
π« 4. Using append()
in a Loop Instead of List Comprehension
squares = []
for i in range(10):
squares.append(i**2)
✅ Use list comprehension for better readability & performance:
squares = [i**2 for i in range(10)]
π« 5. Using +
to Concatenate Lists in a Loop
result = []
for i in range(1000):
result = result + [i] # Creates a new list each time! O(n^2)
✅ Use append()
or extend()
:
result = []
for i in range(1000):
result.append(i) # O(1) operation
OR:
result = list(range(1000)) # Best performance!
π« 6. Modifying a List While Iterating
my_list = [1, 2, 3, 4, 5]
for x in my_list:
if x % 2 == 0:
my_list.remove(x) # Can cause skipped elements!
✅ Use a list comprehension instead:
my_list = [x for x in my_list if x % 2 != 0]
Would you like me to go deeper into any of these? π