Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is list[i:j] guaranteed to be an empty list if list[j] precedes list[i]?

Tags:

python

list

slice

The Python tutorial explains slice behavior when indices are negative, but I can't find documentation describing the behavior when the end index precedes the start index. (I've also looked at Explain Python's slice notation, and perhaps I'm not reading carefully enough, but the answers there don't seem to address this point.)

The behavior that I observe is that an empty list is returned, which seems reasonable to me. However, it also would seem reasonable to me for this to return a list of items between i and j in reversed order or to simply raise an exception.

Is list[i:j] guaranteed to be an empty list if list[j] precedes list[i]?

like image 934
jamesdlin Avatar asked Jan 22 '15 10:01

jamesdlin


People also ask

Can a list be empty?

You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed.

Which function in list returns false when the list is empty?

The isEmpty () method returns the Boolean value 'true' if this list contains no elements, else it returns false.

How do you check if a list is empty in Python?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.

How do you initiate an empty list in Python?

An empty list in Python can be created in two ways, either by using square brackets [] or by using the list() constructor.


1 Answers

Yes, if j <= i is true, the resulting slice is empty, for standard Python types. To get the results in reverse order, you need to add a negative stride:

list[i:j:-1] 

because explicit is better than implicit.

This is documented in Common Sequence Operations, footnote 4:

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

Bold emphasis mine.

Custom types are free to interpret this differently.

like image 108
Martijn Pieters Avatar answered Sep 26 '22 10:09

Martijn Pieters