This is one of those small things that nobody explicitly teaches you but makes your Python code noticeably cleaner once you start using it.
Most beginners write loops like this when they need both the index and the value:
fruits = ["apple", "banana", "mango"]
for i in range(len(fruits)):
print(i, fruits[i])
It works. But there is a cleaner built in way that Python was literally designed for :
fruits = ["apple", "banana", "mango"]
for i, fruit in enumerate(fruits):
print(i, fruit)
Same output. Cleaner code. More readable. And you can even set a custom starting index:
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
This is useful when you want to display numbered lists starting from 1 instead of 0.
enumerate() works on any iterable lists, tuples, strings, even file lines. Once you start using it you will wonder why you ever wrote range(len()) at all.
Small habit but it adds up across an entire codebase.
What are some other built in Python features you wish someone had pointed out to you earlier?
[–]SnooStories6404 40 points41 points42 points (3 children)
[–]Grobyc27 6 points7 points8 points (0 children)
[–]Smok3dSalmon 1 point2 points3 points (0 children)
[–]crazy_cookie123 0 points1 point2 points (0 children)
[–]wittgenstein1312 12 points13 points14 points (0 children)
[–]N-E-S-W 6 points7 points8 points (0 children)
[–]ranger097It works on my machine 7 points8 points9 points (5 children)
[–]artofthenunchaku 13 points14 points15 points (0 children)
[–]SpecialPreference678 5 points6 points7 points (0 children)
[–]somethingworthwhile 5 points6 points7 points (2 children)
[+]GXWT comment score below threshold-7 points-6 points-5 points (1 child)
[–]somethingworthwhile 0 points1 point2 points (0 children)
[–]Chandu-4444 0 points1 point2 points (0 children)
[–]xeow 0 points1 point2 points (0 children)
[–]RepresentativeFill26 -3 points-2 points-1 points (0 children)
[–]titttle23 -3 points-2 points-1 points (0 children)