Page 1 of 1

if list is empty [solved]

Posted: Tue Apr 21, 2020 5:42 am
by lovebby
So I'm essentially trying to get this code working.

Code: Select all

$ list = ['apples','oranges']

"I'm gonna making apple sauce and orange juice."
$list.remove("apples")
$list.remove("oranges")
"The list is empty."
if list == []:
    "I need to buy apples and oranges."
Is there a way to check if the list is empty?

Re: if list is empty

Posted: Tue Apr 21, 2020 6:22 am
by hell_oh_world
lovebby wrote: Tue Apr 21, 2020 5:42 am So I'm essentially trying to get this code working.

Code: Select all

$ list = ['apples','oranges']

"I'm gonna making apple sauce and orange juice."
$list.remove("apples")
$list.remove("oranges")
"The list is empty."
if list == []:
    "I need to buy apples and oranges."
Is there a way to check if the list is empty?
technically, python treats its data types as booleans (True or False)... python magically understands when to consider a data type False or True...
For list you can do that like this...

Code: Select all

default my_list = []
label start:
	if my_list: # this is equivalent to `my_list == []`, you can reverse the condition by setting it to `not my_list`, which is equal to `my_list != []`
		"Your list has one or more elements."
	else:
		"Your list is empty."

Re: if list is empty

Posted: Tue Apr 21, 2020 7:56 pm
by AJFLink
lovebby wrote: Tue Apr 21, 2020 5:42 am So I'm essentially trying to get this code working.

Code: Select all

$ list = ['apples','oranges']

"I'm gonna making apple sauce and orange juice."
$list.remove("apples")
$list.remove("oranges")
"The list is empty."
if list == []:
    "I need to buy apples and oranges."
Is there a way to check if the list is empty?

Code: Select all

$ test_list = ['apples','oranges']

"I'm gonna making apple sauce and orange juice."
$ del test_list[0]
$ del test_list[0]
"This list is empty"
if len(test_list) == 0:
	"I need to buy apples and oranges."
else:
	"This list is not empty."
If you want to have a function that you can use to see if a list/tuple is empty:

Code: Select all

python:
	def isEmptyList(your_list):
			if len(your_list) == 0:
				return True
			return False 
I hope that this helps.

Re: if list is empty

Posted: Tue Apr 21, 2020 8:56 pm
by Imperf3kt
More useful would be checking if the item is in the list, rather than if the list is empty. You might have oranges, but no apples. If you try to make apple juice, you can, despite having no apples, because the list isn't empty.

I learnt how to use python lists here.
https://www.w3schools.com/python/python_lists.asp

An example of how to check if an item is in a list can be found here.
https://www.w3schools.com/python/trypyt ... mo_list_in

Re: if list is empty

Posted: Fri Apr 24, 2020 2:05 pm
by lovebby
Thank you everyone It got it now! And thanks imperfect for that link, there's lots ofinformation thats gonna help me out there haha.