Python list comprehension and more

3 approaches to manipulate data safely

Damjan Dimitrioski
Sep 1, 2018 · 1 min read

Multiple results

One result

Sometimes we want to perform list comprehension, but we have one result

Match

This code will match a value and return one and only one element from the list.

No match

This code will not match any value, but will fall back to the default value, that is None.

No match + no default

This code will not match any value, and will raise an exception StopIteration due to we haven’t provided a default value.

Get n-th result

If for any reason we need to have n-th element of a list

This code will retrieve the n-th element of a list.
The second param i.e 0 controls which element to retrieve i.e 1 will return ‘Petko2’ and 2 or any number bigger than 1 will respond with the default value. Default value is the last 0, next to the bracket.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade