Skip to content Skip to sidebar Skip to footer

How To Know If A List Contains Only 1 Element Without Using Len

I want to know if a list contains only one element, without using len. What is the most pythonic way to do it between these two solutions? Or maybe none of these are pythonic, and

Solution 1:

One of Python's philosophies is, asking for forgiveness is easier than asking for permission (Python glossary).

In this sense, the most Pythonic way to check if a list has at least one element would be trying and access the element at index 0.

try:
    some_list[0]
except IndexError:
    print("some_list is empty").

Note that pop mutates the list, which is not what you want in a test.

Now if you want to check if a list has exactly one element, a succession of try and except could do the job, but it would become unreadable.

The best way is probably a direct len check:

iflen(some_list) == 1:
    print("some_list has exactly one element")

You commented that you did not want to use len.

I suggest you use the succession of try and except that I evoked above:

try:
    l[0]
except IndexError:
    print("length = 0")
else:
    try:
        l[1]
    except IndexError:
        print("length = 1")
    else:
        print("length > 1")

Solution 2:

You don't want to mutate the list in place (eg by using .pop()). To check that the list contains only one element, you could use a couple of try, except statements to check that (1) you can access the first element, and (2) you can't access a second element.

defis_single_item_list(list_to_check):
    #Check that list is not emptytry:
        _ = list_to_check[0]
    except IndexError:
        returnFalse#Return true if list has a single elementtry:
        _ = list_to_check[1]
    except IndexError:
        returnTrue#Return False if more than one elementreturnFalse

Really, the most Pythonic way is to just use len.

Solution 3:

Each list has a length.

iflen(my_list) < 2:
    print("too short")

Post a Comment for "How To Know If A List Contains Only 1 Element Without Using Len"