Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nth element of a python list or a default if not available

Tags:

python

list

I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available?

For example, given a list myList I would like to get myList[0], or 5 ifmyList is an empty list.

Thanks.

like image 481
user265454 Avatar asked Mar 22 '10 12:03

user265454


People also ask

How do you find the nth element of a list in Python?

To get every nth element in a list, a solution is to do mylist[::n].

How do you check if an element doesn't exist in a list in Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count() function.

How do you check if an element is not there in a list?

Use not in to Check if an Element Is Not in a List in Python. If we need to check if an element is not in the list, we can use the not in keyword. The not is a logical operator to converts True to False and vice-versa. So if an element is not present in a list, it will return True .

How do you print the nth element in a list?

In order to print the n th element of every list from a list of lists, you need to first access each list, and then access the n th element in that list. Which could then be called in the form print_nth_element(data, 2) for your case.


1 Answers

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 
like image 115
gruszczy Avatar answered Sep 18 '22 23:09

gruszczy