Negative list index?
Negative numbers mean that you count from the right instead of the left. So, list[-1]
refers to the last element, list[-2]
is the second-last, and so on.
Why does Python return negative list indexes?
In Python, negative list indices indicate items counted from the right of the list (that is, l[-n]
is shorthand for l[len(l)-n]
).
If you find you need negative indices to indicate an error, then you can simply check for that case and raise the exception yourself (or handle it then and there):
index = get_some_index()
if index < 0:
raise IndexError("negative list indices are considered out of range")
do_something(l[index])
Python list indexing from negative to positive indexes
As far as I can tell, you are looking for something like this:
a = [10, 20, 30, 40]
a[-1:] + a[:1] # this is [40, 10]
You could make it behave like this automatically, but that would require a check if b > c
when querying a[b:c]
(keep in mind, that your -1
in the example is actually len(a) - 1
).
Dart List negative indexing does not work
Dart does not support negative indexes.
To access elements relative to the end, you can calculate the index using
print(x[x.length - 1])
You can create a feature request in https://github.com/dart-lang/sdk to get feedback from the language designers.
Array: Insert with negative index
.append(item)
is to append to the end.
.insert(index, item)
inserts to the place before another item. To "insert" to end, use .insert(len(x), item)
.
Read more at Python documentation.
How to return the index of the first non-negative list in a list of lists in Python?
You can use next
with a generator expression and enumerate
+ all
. Your logic is equivalent to finding the index of the first sublist containing all non-negative values.
x = [[-1, -2, -1], [-1, -3, -1], [1, 2, 2]]
res = next((idx for idx, sub in enumerate(x) if all(i >= 0 for i in sub)), None)
# 2
A list comprehension is only useful if you wish to extract indices for all sublists matching a condition. The built-in next
function retrieves the first value from an iterable. If no sublist is found, the specified None
will be returned.
Related Topics
Convert Integer to String in Python
How to Manage Local VS Production Settings in Django
What Is the Purpose of the -M Switch
How to Check If a String Contains an Element from a List in Python
Adding Days to a Date in Python
String Concatenation of Two Pandas Columns
How to Get Monitor Resolution in Python
How to Convert Each Item in the List to String, for the Purpose of Joining Them
Non-Alphanumeric List Order from Os.Listdir()
Importerror: Dll Load Failed: %1 Is Not a Valid Win32 Application. But the Dll's Are There
What Does 'Weight' Do in Tkinter
How to Extract Multiple JSON Objects from One File
How to Turn a Python Datetime into a String, with Readable Format Date
Groupby Results to Dictionary of Lists
Can Not Click on a Element: Elementclickinterceptedexception in Splinter/Selenium