Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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