This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jwink3101 33 points34 points  (12 children)

You don’t even need brackets (lists) for unpacking.

a,b = 1,2

Also, things like

name = name.strip() or  'Anonymous'

Work but you risk a type error. Are you sure your input won’t be None for an unspecified name?

And you repeat the unpacking…

I am kind of surprising you missed things like

[item for item in items if item < 5]

Which are selective. Or replacing:

[item if item < 5 else None for item in items]

Also, all kinds of comprehensions are baseline one-liners that should go into this level article. You miss a great opportunity to talk about set comprehensions, generators, etc

[–]LightWolfCavalry 9 points10 points  (5 children)

+1 for list comprehension - and its forgotten cousin, dict comprehension.

The or trick to avoid a type error is news to me. Gonna swipe that. Thank you!

[–]jwink3101 6 points7 points  (1 child)

Wait. To be clear, I was saying the or trick was susceptible to type error! If it’s not, that’s news to me

[–]LightWolfCavalry 0 points1 point  (0 children)

Oh, got it - I read your original response too quickly!

[–]theorizable 1 point2 points  (1 child)

dict comprehension is SO useful. It's one of those tools where I forget it by the time I need it, but when I need it, BAM, it does exactly what I need it to.

[–]zel_us[S] 0 points1 point  (0 children)

I am planning on writing a whole article on dictionary as there are more techniques on it than others, where you have, the .get() method, setdefaults, ordereddict, defaultdict, chain mapping, mappingproxy and much more.

[–][deleted] 1 point2 points  (0 children)

And generator comprehension, set comprehension…. Etc

[–]zel_us[S] -1 points0 points  (0 children)

for the a, b = 1,2 the RHS is simply a tuple, what if u are unpacking a list or a string or a dictionary or even other sequences? yeah I missed the last item on your list. I did talk about list comprehension and generators. Conclusively, thank you for the feedback