Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Empty List Check in Python

Question please. There is an empty list. If the list is empty, then i would like to print a statement that the list is empty. If for some reasons the list gets appended, then it will just print the list. How should i write a code for that.

shoppinglist = [] if shoppinglist == 'None': print("The list is empty") else: print("There is something")

Dont worry about the appending part. I will see if this fits in the while loop function. For now i need to check if the list is empty or not only. Have used bool and empty keywords. Nothing is working.

1 Answer

Gyorgy Andorka
Gyorgy Andorka
13,811 Points

You could use any of the following (note that the value of an empty list is not None (it has an own object id()) but it evaluates to False in terms of boolean value):

if my_list == []  # trivial solution: the list equals an empty list

if len(my_list) == 0  # length of the list is 0, so the list is empty

if not my_list  # means the same as `if my_list == False` in Python syntax