Hacker News new | ask | show | jobs
by xigoi 1630 days ago
I can think of at least 2 obvious ways to iterate through something: for loops and comprehensions.
2 comments

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]
  >>>
The 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.
Agreed. I've mainly seen the first `append` version in code written by people who've just discovered comprehensions and code golf.

    lst = [range(0, 10, 2)]
That's wrong in multiple ways. You want

    lst = list(range(0, 20, 2))
Ohh, yeah, you're right.
Even simpler!
To 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.