I wish to have variables to control how many elements at the beginning and end of a list to skip e.g.
skip_begin = 1
skip_end = 2
my_list = [9,8,7,6,5]
print(my_list[skip_begin:-skip_end])
returns [8, 7].
As Why does slice [:-0] return empty list in Python shows, having skip_end = 0 gives an empty list.
In this case, I actually want just my_list[skip_begin:].
my_list[skip_begin:-skip_end if skip_end != 0 else '']
doesn't work. How can I return an empty value in the ternary operation?
I'd rather use the ternary operation inside the "[ ]" rather than do
my_list[skip_begin:-skip_end] if skip_end != 0 else my_list[skip_begin:]
or an if-else block.
my_list[skip_begin:-skip_end if skip_end != 0 else None]
The problem with your first solution is that the index slicing expects a number (or null value), not a string.
Alternatively:
my_list[skip_begin:-skip_end or None]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With