how to check if this list is empty?
l = ['',['']]
I tried solutions from how to find if nested lists are empty. but none of them worked.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
return all( map(isListEmpty, inList) )
return False # Not a list
You should check if the list is falsy/empty first before recursively checking the list items. You can also avoid explicitly returning True or False by using the and and or operators:
def isListEmpty(inList):
return inList == '' or isinstance(inList, list) and (not inList or all(map(isListEmpty, inList)))
Demo: https://repl.it/repls/AccurateSmallOutcome
For lists that actually are empty, the function should simply return True.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
if len(inList) == 0:
return True
else:
return all(map(isListEmpty, inList))
return False # Not a list
l is not empty in fact. But in this case this code should work:
l = ['',['']]
def isListEmpty(inList):
for char in inList:
if char == '' or ['']:
return True
else:
return False
break
print(isListEmpty(l))
You can use a simple recursive approach with any. Using any would make sure that the recursively search ends as soon as a non empty item is found
>>> def is_non_empty_list (l):
... return any(is_non_empty_list(e) if isinstance(e, list) else e for e in l)
...
>>> def is_empty_list (l):
... return not is_non_empty_list(l)
...
>>> is_empty_list(['', ['']])
True
>>> is_empty_list(['', ['a']])
False
>>>
Try This
l = [' ',[ ]]
def isListEmpty(thisList):
for el in thisList:
if (len(el)==0 and type(el)==list):
print('empty') # Or whatever you want to do if you encounter an empty list
isListEmpty(l)
If you face any problems comment below
Related
If I have string needle and I want to check if it exists contiguously as a substring in haystack, I can use:
if needle in haystack:
...
What can I use in the case of a non-continuous subsequence? Example:
>>> haystack = "abcde12345"
>>> needle1 = "ace13"
>>> needle2 = "123abc"
>>> is_subsequence(needle1, haystack)
True
>>> is_subsequence(needle2, haystack) # order is important!
False
I don't know if there's builtin function, but it is rather simple to do manually
def exists(a, b):
"""checks if b exists in a as a subsequence"""
pos = 0
for ch in a:
if pos < len(b) and ch == b[pos]:
pos += 1
return pos == len(b)
>>> exists("moo", "mo")
True
>>> exists("moo", "oo")
True
>>> exists("moo", "ooo")
False
>>> exists("haystack", "hack")
True
>>> exists("haystack", "hach")
False
>>>
Using an iterator trick:
it = iter(haystack)
all(x in it for x in needle)
This is only a concise version of the same idea presented in tobias_k's answer.
Another possibility: You can create iterators for both, needle and haystack, and then pop elements from the haystack-iterator until either all the characters in the needle are found, or the iterator is exhausted.
def is_in(needle, haystack):
try:
iterator = iter(haystack)
for char in needle:
while next(iterator) != char:
pass
return True
except StopIteration:
return False
We can try simple for loop and break method and pass on substring once the match is found
def substr(lstr,sstr):
lenl = len(lstr)
for i in sstr:
for j in range(lenl):
if i not in lstr:
return False
elif i == lstr[j]:
lstr = lstr[j+1:]
break
else:
pass
return True
I need to code a function that takes as input a list of tuples, the number of tuples, and two numbers. This function should return True if the two given numbers exist in one of the tuples in our list.
For example : ma_fonction(l,n,i,j)
l: list of tuples
i and j two numbers between 0 and n-1 and i != j
I tried this code:
def ma_fonction(l,n,i,j):
checker = False
for item in l :
if ( i in item and j in item ):
cheker = True
return True
else:
return False
ma_fonction([(0,1), (5,2), (4,3)], 6, 2, 5)
But it doesn't work. What should I add or change?
I tried this ( somehow i didnt copy all my work in my question )
This is my work:
def ma_fonction(l,n,i,j):
checker = False
if((i!=j )and (0<=i<=n-1 )and( 0<=j<=n-1) ):
for item in l :
if ( i in item and j in item ):
cheker=True
return True
else:
return False
change your function to this:
def foo(l,n,i,j):
for item in l:
if (i in item and j in item):
return True
return False
You go over all tuples, and if i and j are in the tuple, you return True.
If it went over all tuples and didn't find a match, we can be sure that we can return False.
And this implementation really doesn't need the parameter n
The logic is that for each tuple in this list, check whether it contains the number i and j. If yes, then return True; if no, continue check the next tuple. Once you finish checking every tuple, and it turns out that there is no satisfied tuple, then return False.
def ma_fonction(l,n,i,j):
for item in l :
if ( i in item and j in item ):
return True
return False
This should work:
def ma_fonction(l,n,i,j):
for item in l :
if ( i in item and j in item ):
return True
return False
The reason your solution is not working is because you are returning False at the first element of the list that doesn't match with i and j. What you need to do is return False if and only if you looked in all the elements of the list and you couldn't find a match.
I am trying to make a function that is able to find a element in a nested list.
That is what if got so far:
def in_list(ele, lst, place):
if ele == lst[place]:
return True
else:
for i in range(len(lst)):
in_list(ele, lst[i], place)
This is what i input:
a=[[1,2],[3,4]]
if in_list(2,a,1)==True:
print("True")
the variable "place" is the place in the list where the element should be found...
Now somehow it doesn't understand this line if ele == lst[place]
this is the error message: TypeError: 'int' object is not subscriptable
Thanks in advance
There are two issues in the last line
def in_list(ele, lst, place):
if ele == lst[place]:
return True
else:
for i in range(len(lst)):
in_list(ele, lst[i], place)
lst[i] is an integer (assuming lst is a list of integers), which is why you get your error.
The other issue is that you're not returning anything from the else branch.
Something like this might work better in case of arbitrary, but uniform, nesting:
def recursive_contains(item, lst):
if len(lst) == 0:
return False
elif isinstance(lst[0], collections.Iterable):
return any(recursive_contains(item, sublist) for sublist in lst)
else:
return item in lst
for arbitrary non-uniform nesting, perhaps something like this:
def recursive_contains(item, lst):
if not isinstance(lst, collections.Iterable):
return item == lst
for val in lst:
if item == val:
return True
elif isinstance(val, collections.Iterable):
if recursive_contains(item, val):
return True
return False
of course if you only have 2 levels (all elements of lst are lists of int), you could simply say:
if ele in sum(lst, []):
...
which uses sum to flatten the list first.
The other answers well define the mistake in your code.
Just to reiterate that you were assuming each element in the list as a nested list and subscripting it like - elem[place].
You can't subscript a primitive type such as integer and hence the error.
Refer the below code to handle nesting.
Note - You Don't require the 3rd parameter of place, more appropriately you wouldn't the place if you are searching.*
def fetch(data, l):
for element in l:
if type(element) == list:
if fetch(data, element):
return True
else:
if element == data:
return True
return False
On further thought you are looking for an element that should be only at "place" index of any of the nested lists.
Refer to the snippet below for that-
def fetch(data, l,place):
if data == l[place]:
return True
else:
for element in l:
if type(element) == list and fetch(data,element,place):
return True
return False
Note- Only call fetch again if the element is a list.
a = [[1, 2], [3, 4]]
def inlist(e, l, p):
for lists in range(len(l)):
print("array:", l[lists])
print("Looking for", e)
print("In position", p)
print(l[lists][p])
if l[lists][p] == e:
print(True, ": The element ", e, " is in the list n.", lists, " at the place ", p)
return True
inlist(2, a, 1)
Output
array: [1, 2]
Looking for 2
In position 1
2
True : The element 2 is in the list n. 0 at the place 1
I have an assignment I've been stuck on for a couple days now. I have to recursively figure out if a list has repeats but I cannot use any loops or built in functions besides len(). I'm also not allowed to use the 'in' function. Returns True if list L has repeats, False otherwise. This is what I've been able to figure out:
def has_repeats(L):
if len(L) <= 1:
return False
elif L[0] == L[1]:
return True
else: return has_repeats(L[0] + L[2:])
But the problem with that is it's only comparing the first element to the rest, instead of each element to the rest. I can't figure out how to do that without a running counter or something. Any suggestions?
You almost have it. Along with checking the first element with the rest of the list, you also need to check the second the same way:
def has_repeats(L):
if len(L) <= 1:
return False
if L[0] == L[1]:
return True
if has_repeats([L[0]] + L[2:]):
return True
if has_repeats(L[1:]):
return True
return False
You can also compact this into the following representation:
def has_repeats(L):
return len(L)>1 and L[0]==L[1] or has_repeats([L[0]]+L[2:]) or has_repeats(L[1:])
Use a helper function:
def helper(ele, rest):
if not rest:
return False
return ele == rest[0] or helper(ele, l[1:])
def has_repeats(l):
if not l:
return False
return helper(l[0], l[1:]) or has_repeats(l[1:])
How can I find out if a list is empty without using the not command?
Here is what I tried:
if list3[0] == []:
print("No matches found")
else:
print(list3)
I am very much a beginner so excuse me if I do dumb mistakes.
In order of preference:
# Good
if not list3:
# Okay
if len(list3) == 0:
# Ugly
if list3 == []:
# Silly
try:
next(iter(list3))
# list has elements
except StopIteration:
# list is empty
If you have both an if and an else you might also re-order the cases:
if list3:
# list has elements
else:
# list is empty
You find out if a list is empty by testing the 'truth' of it:
>>> bool([])
False
>>> bool([0])
True
While in the second case 0 is False, but the list [0] is True because it contains something. (If you want to test a list for containing all falsey things, use all or any: any(e for e in li) is True if any item in li is truthy.)
This results in this idiom:
if li:
# li has something in it
else:
# optional else -- li does not have something
if not li:
# react to li being empty
# optional else...
According to PEP 8, this is the proper way:
• For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq)
if not len(seq)
You test if a list has a specific index existing by using try:
>>> try:
... li[3]=6
... except IndexError:
... print 'no bueno'
...
no bueno
So you may want to reverse the order of your code to this:
if list3:
print list3
else:
print "No matches found"
Check its length.
l = []
print len(l) == 0
this is how you would do that
if len(list3) == 0:
print("No matches found")
Python provides an inbuilt any() function to check whether an iterable is empty or not:
>>>list=[]
>>>any(list)
False
The function returns True if the iterable contains a 'True' value, and False otherwise.
However, note that the list [0] also returns False with any().