5 ms·
You're right that both iterate through something but `for` loops and comprehensions aren't used as if they were interchangeable. For example, you'll sometimes
by voltagedivider 5y ago
You're right that both iterate through something but `for` loops and comprehensions aren't used as if they were interchangeable.
For example, you'll sometimes see people do bad stuff like this:
>>> lst = []
>>>
>>> [lst.append(i + i) for i in range(10)]
[None, None, None, None, None, None, None, None, None, None]
>>>
>>> lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
When they should be doing this:
>>> lst = []
>>>
>>> for i in range(10):
... lst.append(i + i)
...
>>> lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
Or just this:
>>> lst = [i + i for i in range(10)]
>>>
>>> lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
- a_t48 5y agolst = [range(0, 10, 2)]
- orlp 5y agoThat's wrong in multiple ways. You want lst = list(range(0, 20, 2))
- a_t48 5y agoOhh, yeah, you're right.
- voltagedivider 5y agoEven simpler!
- jstx1 5y agoThe first append version will more often be in a loop. It's unlikely that someone will know enough to use comprehensions but not enough to still use append.
- voltagedivider 5y agoAgreed. I've mainly seen the first `append` version in code written by people who've just discovered comprehensions and code golf.