Intermediate Tips
1.List Comprehensions for Filtering
- Filter and create a list in one line:
pythonCopy codenumbers = [1, 2, 3, 4, 5]
evens = [x for x in numbers if x % 2 == 0]
print(evens) # Output: [2, 4]
2.Dictionary Comprehensions
- Create a dictionary using comprehension:
pythonCopy codenumbers = range(5)
squares = {x: x*x for x in numbers}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3.Use Counter from collections
- Count occurrences in a list:
pythonCopy codefrom collections import Counter
fruits = ['apple', 'banana', 'apple', 'cherry']
counts = Counter(fruits)
print(counts) # Output: Counter({'apple': 2, 'banana': 1, 'cherry': 1})
4.Check Memory Usage with sys.getsizeof()
- Check how much memory an object uses:
pythonCopy codeimport sys
data = [1, 2, 3]
print(sys.getsizeof(data)) # Output: Memory size in bytes
5.Use itertools for Infinite Iterators
- Create infinite counters:
pythonCopy codefrom itertools import count
for i in count(5):
if i > 10:
break
print(i)
# Output: 5, 6, 7, 8, 9, 10
6.Flatten a Nested List with List Comprehension
- Combine lists of lists into a single list:
pythonCopy codenested = [[1, 2], [3, 4]]
flat = [item for sublist in nested for item in sublist]
print(flat) # Output: [1, 2, 3, 4]
7.Lambda Functions for Short Functions
- Use lambda for concise functions:
pythonCopy codesquare = lambda x: x * x
print(square(5)) # Output: 25
8.Use set() to Remove Duplicates
- Quickly remove duplicates from a list:
pythonCopy codemy_list = [1, 2, 2, 3, 3, 3]
unique = list(set(my_list))
print(unique) # Output: [1, 2, 3]
9.Swap Variables
- Swap two variables in one line:
pythonCopy codea, b = 1, 2
a, b = b, a
print(a, b) # Output: 2, 1
10.Get Unique Elements Using set()
- Extract unique values from a list:
pythonCopy codenumbers = [1, 2, 3, 1, 2]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3}