9

What is the easiest way to check to see if a list or dict exists in python ?

Im using the following but this isn't working:

if len(list) == 0:
    print "Im not here"

Thanks,

Reinout van Rees
  • 13,486
  • 2
  • 36
  • 68
felix001
  • 15,341
  • 32
  • 94
  • 121
  • 3
    If there is no object that you've created named `list` in scope, this code will be trying to obtain the length of the built in `list` type. This will result in exception `TypeError`. – mhawke Jul 19 '12 at 08:06

8 Answers8

13

For the lists:

if a_list:
    print "I'm not here"

The same is for the dicts:

if a_dict:
    print "I'm not here"
warvariuc
  • 57,116
  • 41
  • 173
  • 227
Igor Mandric
  • 172
  • 3
  • 3
    `list` and `dict` are built in types. This code will always succeed, i.e. the conditions in the `if` statements. – mhawke Jul 19 '12 at 08:08
  • @mhawke, a_list = list(), bool(a_list) -> False, same for a_dict, and "if statement" is False insensitive. If a_list, a_dict not defined, then we'll have a wonderful and amazing Exception! :) –  Oct 31 '13 at 16:09
  • @VitalieGhelbert please see the question's revision history - the question has been edited after my comment was made. – mhawke Nov 12 '13 at 07:52
  • @mhawke, ok, tx u. :) –  Nov 12 '13 at 11:35
  • 4
    WHAT? You mean `if not a_list: print "I am not here"`?? – return 0 Oct 04 '15 at 16:57
  • 1
    Perhaps that used to work, but not with 3.7. The try/except solutions below are better – Mark Burgoyne Feb 15 '19 at 05:00
11

You can use a try/except block:

try:
    #work with list
except NameError:
    print "list isn't defined"
Nicolas
  • 5,583
  • 1
  • 25
  • 37
6

When you try to reference a non-existing variable the interpreter raises NameError. It's not safe, however, to rely on the existence of a variable in your code (you'd better initialize it to None or something). Sometimes I used this:

try:
    mylist
    print "I'm here"
except NameError:
    print "I'm not here"
dawe
  • 463
  • 2
  • 8
4

If you're able to name it - it obviously "exists" - I assume you mean to check that it's "non-empty"... The most pythonic method is to use if varname:. Note, this won't work on generators/iterables to check if they will return data as the result will always be True.

If you just want to use a certain index/key, then just try and use it:

try:
    print someobj[5]
except (KeyError, IndexError) as e: # For dict, list|tuple
    print 'could not get it'
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
2

Examples:

mylist=[1,2,3]
'mylist' in locals().keys()

Or use this:

mylist in locals().values()
Community
  • 1
  • 1
k99
  • 709
  • 2
  • 6
  • 13
1

Simple console test:

>>> if len(b) == 0: print "Ups!"
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

>>> try:
...     len(b)
... except Exception as e:
...     print e
... 
name 'b' is not defined

Examples show how to check if a list has elements:

alist = [1,2,3]
if alist: print "I'm here!"

Output: I'm here!

Otherwise:

alist = []
if not alist: print "Somebody here?"

Output: Somebody here?

If you need to check existence/nonexistence of a list/tuple maybe this can be of help:

from types import ListType, TupleType
a_list = [1,2,3,4]
a_tuple = (1,2,3,4)

# for an existing/nonexisting list
# "a_list" in globals() check if "a_list" is defined (not undefined :p)

if "a_list" in globals() and type(a_list) is ListType: 
    print "I'm a list, therefore I am an existing list! :)"

# for an existing/nonexisting tuple
if "a_tuple" in globals() and type(a_tuple) is TupleType: 
    print "I'm a tuple, therefore I am an existing tuple! :)"

If we need to avoid of in globals() maybe we can use this:

from types import ListType, TupleType
try:
    # for an existing/nonexisting list
    if type(ima_list) is ListType: 
        print "I'm a list, therefore I am an existing list! :)"

    # for an existing/nonexisting tuple
    if type(ima_tuple) is TupleType: 
        print "I'm a tuple, therefore I am an existing tuple! :)"
except Exception, e:
    print "%s" % e

Output:
    name 'ima_list' is not defined
    ---
    name 'ima_tuple' is not defined

Bibliography: 8.15. types — Names for built-in types — Python v2.7.3 documentation https://docs.python.org/3/library/types.html

gunr2171
  • 16,104
  • 25
  • 61
  • 88
0

Check (1) variable exist and (2) check it is list

try:
    if type(myList) is list:
        print "myList is list"
    else:
        print "myList is not a list"
except:
    print "myList not exist"
Chemical Programmer
  • 4,352
  • 4
  • 37
  • 51
-1
s = set([1, 2, 3, 4])
if 3 in s:
    print("The number 3 is in the list.")
else:
    print("The number 3 is NOT in the list.")

You can find more about it here: https://docs.quantifiedcode.com/python-anti-patterns/performance/using_key_in_list_to_check_if_key_is_contained_in_a_list.html

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Eda
  • 1
  • 1