Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return nothing for Python list slicing

Tags:

python

list

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.

like image 904
Gnubie Avatar asked Dec 11 '22 11:12

Gnubie


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

Alternatively:

my_list[skip_begin:-skip_end or None]
like image 69
yinnonsanders Avatar answered Dec 19 '22 01:12

yinnonsanders