How to get the nth element of a python list or a default if not available
l[index] if index < len(l) else default
To support negative indices we can use:
l[index] if -len(l) <= index < len(l) else default
How do I get the last element of a list?
some_list[-1]
is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The some_list[-n]
syntax gets the nth-to-last element. So some_list[-1]
gets the last element, some_list[-2]
gets the second to last, etc, all the way down to some_list[-len(some_list)]
, which gives you the first element.
You can also set list elements in this way. For instance:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
Note that getting a list item by index will raise an IndexError
if the expected item doesn't exist. This means that some_list[-1]
will raise an exception if some_list
is empty, because an empty list can't have a last element.
Accessing nth element of list of lists python - index does not exist error
You could use a conditional list comprehension to check the length of the inner lists and index them only if they are above a certain length:
index = 1
[i[index] if len(i)>index else float('nan') for i in list_of_numbers]
# [10, 8, nan, 0, nan]
Get value at list/array index or None if out of range in Python
Try:
try:
return the_list[i]
except IndexError:
return None
Or, one liner:
l[i] if i < len(l) else None
Example:
>>> l=list(range(5))
>>> i=6
>>> print(l[i] if i < len(l) else None)
None
>>> i=2
>>> print(l[i] if i < len(l) else None)
2
Getting a default value on index out of range in Python
In the Python spirit of "ask for forgiveness, not permission", here's one way:
try:
b = a[4]
except IndexError:
b = 'sss'
Why does python return the n+1th list element rather than the nth?
Python uses something that is called zero based indexing, which means that the first element in a list is referred to element number 0 and not 1.
A quick way to return list without a specific element in Python
>>> suits = ["h","c", "d", "s"]
>>> noclubs = list(suits)
>>> noclubs.remove("c")
>>> noclubs
['h', 'd', 's']
If you don't need a seperate noclubs
>>> suits = ["h","c", "d", "s"]
>>> suits.remove("c")
How to get the nth element of a python list or a default if not available
l[index] if index < len(l) else default
To support negative indices we can use:
l[index] if -len(l) <= index < len(l) else default
Why doesn't list have safe get method like dictionary?
Ultimately it probably doesn't have a safe .get
method because a dict
is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as the len
method is very fast). The .get
method allows you to query the value associated with a name, not directly access the 37th item in the dictionary (which would be more like what you're asking of your list).
Of course, you can easily implement this yourself:
def safe_list_get (l, idx, default):
try:
return l[idx]
except IndexError:
return default
You could even monkeypatch it onto the __builtins__.list
constructor in __main__
, but that would be a less pervasive change since most code doesn't use it. If you just wanted to use this with lists created by your own code you could simply subclass list
and add the get
method.
Related Topics
Is There Any Difference Between "Foo Is None" and "Foo == None"
Pandas Create New Column with Count from Groupby
How to Create an Encrypted Zip File
Accessing Every 1St Element of Pandas Dataframe Column Containing Lists
How to Find Where Python Is Installed on Windows
Combining Conda Environment.Yml with Pip Requirements.Txt
How to Force Python to Be 32-Bit on Snow Leopard and Other 32-Bit/64-Bit Questions
How to Select Python Version in Pycharm
Python Random Sample with a Generator/Iterable/Iterator
Processing Single File from Multiple Processes
Reference List Item by Index Within Django Template
Why 'Torch.Cuda.Is_Available()' Returns False Even After Installing Pytorch with Cuda
How to Set Folder Permissions in Windows
Query for List of Attribute Instead of Tuples in SQLalchemy
Setting an Environment Variable in Virtualenv