How to return nothing for slicing a Python list

I want to have variables to control the number of items at the beginning and end of the list to skip for example.

skip_begin = 1
skip_end = 2
my_list = [9,8,7,6,5]
print(my_list[skip_begin:-skip_end])

      

returns [8, 7].

How Why does slice [: -0] return an empty list in Python shows that skip_end = 0 gives an empty list.

In this case, I really want to just my_list [skip_begin:].

my_list[skip_begin:-skip_end if skip_end != 0 else '']

      

does not work. How can I return empty value in ternary operation?

I would rather use the ternary operation inside "[]" rather than

my_list[skip_begin:-skip_end] if skip_end != 0 else my_list[skip_begin:]

      

or an if-else block.

+3


source to share


3 answers


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), not a string.



As an alternative:

my_list[skip_begin:-skip_end or None]

      

+8


source


my_list[skip_begin:-skip_end if skip_end else None]

      

Your line:

my_list[skip_begin:-skip_end if skip_end != 0 else '']

      



could get you on the right track because it gives:

TypeError: slice indexes must be integer or None or have an __index__ Method

I am inspired by the previous answer, but the if skip_end != 0

same asskip_end

+6


source


 my_list[skip_begin:-skip_end if skip_end != 0 else skip_begin:]

      

-1


source







All Articles