Please Note: This is going to be a long series of how I’d train an intern to write Python code. It is truly written based on my experience and knowledge and I’d appreciate you highlighting and adding your comments to it
Starting as a Python intern? It’s exciting, no doubt.
If you’re starting out or mentoring a new developer, these insights will be invaluable.
1. List Comprehensions
Now, what are List Comprehensions?
A compact way to create lists in Python.
Instead of writing lengthy loops, you can generate new lists in a single line.
Imagine you need to square numbers in a list:
numbers = [1, 2, 3, 4, 5]
squared = []
for n in numbers:
squared.append(n ** 2)The List Comprehension Way
squared = [n**2 for n in numbers]Why It Matters
- Readable: Code is easier to scan.
- Faster: Python executes list comprehensions faster than
forloops.
2. Enumerate: Simplifying Index Tracking
What’s Enumerate?
enumerate() lets you loop through a list with an index — without manually creating counters :)
Before Enumerate
fruits = ["apple", "banana", "cherry"]
index = 0
for fruit in fruits:
print(f"#{index}: {fruit}")
index += 1Using Enumerate
for index, fruit in enumerate(fruits):
print(f"#{index}: {fruit}")Why It Matters
- Cleaner Code: No need for external counters.
- Reduces Bugs: You won’t forget to increment your index variable.
It keeps code clean and logical.
3. setdefault() and defaultdict
The Problem? Missing Keys in Dictionaries
Example Without setdefault
data = {}
key = 'name'
if key not in data:
data[key] = 'SK'
print(data) # {'name': 'SK'}Using setdefault
setdefault() reduces the check to one line:
data = {}
data.setdefault('name', 'Shashwat')
print(data) # {'name': 'Shashwat'}- Behaviour: If the key exists,
setdefaultdoes nothing. - Benefit: Saves time and avoids manual checks.
defaultdict? Another Smarter Alternative ;)
collections.defaultdict automatically initializes missing keys with a default value.
Example Without defaultdict
When counting word occurrences:
words = ['apple', 'banana', 'apple']
count = {}
for word in words:
if word not in count:
count[word] = 0
count[word] += 1
print(count)Using defaultdict:
from collections import defaultdict
words = ['apple', 'banana', 'apple']
count = defaultdict(int)
for word in words:
count[word] += 1
print(count) # defaultdict(<class 'int'>, {'apple': 2, 'banana': 1})Why It Matters
- Saves Time: No manual key-checking.
- Cleaner Code: Focus on logic, not handling missing keys.
Part 1 of the article can be accessed here :)
In case we are meeting for the first time, come over here, it’ll be worth the roller coaster of articles that are gonna come up in the next few weeks.
Enjoyed the read? You can support my writing journey here — Buy me a coffee?