if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite Pythonic.
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite Pythonic.
The Pythonic way to do it is from the PEP 8 style guide.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
How do I check if this list is "empty"?
What's the most pythonic way of checking if variable is None or empty string ""?
Videos
I'm completely stumped on a computer science assignment because our lecturer has given us zero information. We're supposed to have the user input a list and check if the list is in decreasing order and print a suitable message if it is. That part works fine. However, if the list is "empty" (I'll explain the quotations in a second) then it should print the list is empty.
The problem is that, according to our brief we're supposed to use .split(",") in order to allow the user to separate their numbers with commas. The problem lies in the fact that even if a user hits enter without inputting anything, the list is still '1' long with just an empty string. I've been scouring the web to find out how to check if a list is empty. But all the tutorials have so far just been in relation to actually empty lists (as in, list = []). One did use the all() function to check that all items in the list were strings, which did work and let me print that the list is empty, but broke the original function. Could someone please help me I'm tearing my hair out with this.
--
def checkOrder():
# checks, etc.
integer_list = []
listLength = len(integer_list)
increasing = 0
decreasing = 0
singleValue = 0
# Converting inputted numbers into a split list
userInput = input("Please enter your numbers seperated by a comma (,):")
inputtedStrings = userInput.split(",")
for number in inputtedStrings:
inputtedIntegers = int(number)
integer_list.append(inputtedIntegers)
# Enumerating list
for i, val in enumerate(integer_list[:-1]):
if val <= integer_list[i+1]:
increasing = 1
elif val >= integer_list[i+1]:
decreasing = 1
# Check for a single value
if len(integer_list) == 1:
singleValue = 1
if len(integer_list) == 1 and
print("The list is empty.")
if increasing == 1:
print("The numbers are in increasing order.")
elif decreasing == 1 or singleValue == 1:
print("The numbers are in decreasing order.")
checkOrder()
--
I'm trying to constantly check against any of those values but I don't want to keep repeating myself in code.
if variable is None or variable == "": do stuff
What are my options? Can I create somehow a class and check against that class?
if variable is MyNewClass: do stuff
How would I write such a class?
Thanks!