Python list comprehension and more
3 approaches to manipulate data safely
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.
