It’s always fun when you stumble across something in your programming toolkit that you had never noticed. Here are three things I’ve recently enjoyed learning.
- Ternary syntax
a = int(raw_input()) is_even = True if a % 0 == 0 else False
- Enumerate
I’ve been looping over the length of my list, all these years, like a chump. It turns out you can do this:
for index, item in enumerate(some_list): # now the index of each item is available as well as the item
# Don't do do this for index in range(len(some_list)): item = some_list[index]
- for… else
Every so often, you really need to know that a for loop has run to completion. That’s what for…else is for!
for item in iterable:
if item % 0 == 0:
first_even_number = item
else:
raise ValueError('No even numbers')