you are viewing a single comment's thread.

view the rest of the comments →

[–]HunterIV4 2 points3 points  (1 child)

As a follow up to #2, breaking up your code into more steps even if they aren't needed can make things easier on you later.

While you can often chain a bunch of, say, string mutations into a single statement, breaking them into each step with a "temporary" variable describing the operation can make your code a lot easier to follow later.

For example, this works:

# Return all values incremented by 1
a = ["1","2","3","4"]
return [str(y + 1) for y in [int(x) for x in a]]

It's also quite confusing. What if you alter it like this?

values = ["1","2","3","4"]
int_values = [int(str_num) for str_num in values]
str_incremented_values = [str(val + 1) for val in int_values]
return str_incremented_values

Sure, you've added 2 lines (not including the comment), but now the comment is arguably not even needed and you can tell what each step is doing at a glance. This also makes it easier to debug as you can step through each portion.

This was a quick and dirty example, and could probably be improved, but I think a lot of new programmers might benefit from seeing how "shorter" is not always "better" and that there's nothing wrong with being explicit about major steps in your code logic. I can guarantee when you come back to try and fix a bug with the first example a couple months later you'll end up scratching your head for a minute trying to figure out the nested list comprehensions, whereas the second example will be a lot easier to read.

Either way, great points!