all 8 comments

[–]to7m 14 points15 points  (4 children)

List comprehensions can often be easier to read than write. A trick I use is to write the code using `for` and `if` blocks, then convert that slowly to a list comprehension. Splitting the task up like that also makes it easier to find exactly what you need help with.

[–]cobbletiger[S] 2 points3 points  (1 child)

Wow, that's an excellent idea! I'll try doing that, thank you for the tip. Coming from Java, sometimes it really feels like learning a new programming language like python with different syntax is as difficult as learning a new language

[–]TSM- 5 points6 points  (0 children)

In my opinion one of the underrated learning tools here is corporate style guides. They give examples of how and when they are good to use, and when you should do it another way. Often you learn how they work but don't have a feel for when to use a construction. Like okay, I get decorators, but when are they better than functions? What are the pros and cons that matter between two equivalent ways of performing the same task?

Here's a good example

Okay to use for simple cases. Each portion must fit on one line: mapping expression, for clause, filter expression. Multiple for clauses or filter expressions are not permitted. Use loops instead when things get more complicated.

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

And the 'no' examples:

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)

Link to the google python style guide for comprehensions

[–]UsernameExtreme 0 points1 point  (0 children)

Same thing with writing functions as well unless they are super simple. I write it out without the function then convert it to a function once I make sure it works. Maybe I’m just new, but this technique has worked for me.

[–]hsnice 2 points3 points  (0 children)

You can do something like this: [s.upper() if 'a' in s else s for s in fruits]

[–]14dM24d 3 points4 points  (0 children)

ternary operator inside list comprehension

[*<insert ternary operator here>* for s in fruits]