3 ms·
I can think of at least 2 obvious ways to iterate through something: for loops and comprehensions.
by xigoi 5y ago
I can think of at least 2 obvious ways to iterate through something: for loops and comprehensions.
- voltagedivider 5y agoYou'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.
- dragonwriter 5y agoTo generate a list/dictionary/geneator from an input iterable, you use a comprehension of the appropriate type. To iterate through it without doing one of those things, you use a for loop. In “one obvious way to do it”, “it” refers to a concrete task; the same is not necessarily intended to be true of arbitrarily broad generalizations of classes of tasks.