Hacker News new | ask | show | jobs
by voltagedivider 1630 days 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]
  >>>
2 comments

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!