Python – check if a letter is in a list
Question:
If a letter (string) is in a list,
find_letter([‘o’, [‘hello’, ‘c’, ‘bye’]),
return True, if not return False.
def find_letter(lst):
lst=['o','hello', 1]
n='o'
if not lst:
return 0
elif lst[0] == n:
return True
elif find_letter(lst[0:]):
return True
else:
return False
print(find_letter(lst))
It does return ‘True’, but I am not sure if this is the right way to do this. Maybe there’s a better way? In the second elif-statement, is python going through all the elements in the list if the first one doesn’t contain the letter? The function must be recursive.
Answers:
I think the most pythonic approach would be to use
def find_letter(letter, lst):
return any(letter in word for word in lst)
The beauty of this is that it iterates over lst
and returns as soon as one of the words in that list contains letter
. Also, it doesn’t need to recurse.
This returns False
instead of 0
if lst
is empty, though (unlike your program) but since False
evaluates to 0
anyway (and vice versa), that’s not really an issue.
You want to find the Membership
Please refer this code to resolve your problem.
Suppose
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
print 3 in list2
Output:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
True
Just realized OP wants to check A string only
You can define a function and match the string in a list recursively like this:
def plist(lst, n):
# loop inside the list
for each in lst:
# if "each" is also a list (nested), check inside that list, too
if isinstance(each, list):
# this will reuse your "plist" and loop over any nested list again
plist(each, n)
# if n matches any element in the list, return True
if any(n in each_letter for each_letter in each):
return True
# if after looping over your list + nested list, return False if no match is find
else:
return False
>> lst = ['o', ['hello', 'c', 'bye']]
>> plist(lst, 'o')
>> True
>> plist(lst, 'h')
>> True
>> plist(lst, 'z')
>> False
Hope this solves your problem.
Here is your error
def find_letter(lst): # You receive your list as lst
lst=['o','hello', 1] # Opppsss! You override it. It does not matter what you receive with lst above, now its value is ['o','hello', 1]
n='o'
So in find_letter(lst[0:])
, you use list slicing, but on lst=['o','hello', 1]
line, you override it again and you always execute your search on the first element of the list.
n = "o" # you can set this too, but this is optional
def find_letter(lst):
# do not set a value to lst in here
if not lst:
return 0
elif lst[0] == n: # You checked first element in here
return True
elif find_letter(lst[1:]): # since you checked the first element, skip it and return the orher elements of the list
return True
else:
return False
lst = ['o','hello', 1]
print find_letter(lst)
Since you need a recursive version:
Short version
def find_letter(let, lst):
return (lst or False) and
((isinstance(lst[0], str) and let in lst[0]) or find_letter(let, lst[1:]))
More explicit version
def find_letter(let, lst):
if lst:
e = lst[0]
return (isinstance(e, str) and let in e) or find_letter(let, lst[1:])
return False
Even more explicit version
def find_letter(let, lst):
if lst:
e = lst[0]
if isinstance(e, str) and let in e:
return True
return find_letter(let, lst[1:])
return False
Note that I leave out a couple of else:
because they are not necessary after a return
statement. If you don’t want to test for a letter in a string, but just for equality, replace let in ...
by let == ...
.
Here is a one line lambda:
any(list(map(lambda x: True if n in str(x) else False,lst )))
data:
lst=['o','hello', 1]
n='o'
output 1:
True
note:
any()
checks if any True
, then True
– otherwise False
– so without the any()
we get:
list(map(lambda x: True if n in str(x) else False,lst ))
output 2:
[True, True, False]
If a letter (string) is in a list,
find_letter([‘o’, [‘hello’, ‘c’, ‘bye’]),
return True, if not return False.
def find_letter(lst):
lst=['o','hello', 1]
n='o'
if not lst:
return 0
elif lst[0] == n:
return True
elif find_letter(lst[0:]):
return True
else:
return False
print(find_letter(lst))
It does return ‘True’, but I am not sure if this is the right way to do this. Maybe there’s a better way? In the second elif-statement, is python going through all the elements in the list if the first one doesn’t contain the letter? The function must be recursive.
I think the most pythonic approach would be to use
def find_letter(letter, lst):
return any(letter in word for word in lst)
The beauty of this is that it iterates over lst
and returns as soon as one of the words in that list contains letter
. Also, it doesn’t need to recurse.
This returns False
instead of 0
if lst
is empty, though (unlike your program) but since False
evaluates to 0
anyway (and vice versa), that’s not really an issue.
You want to find the Membership
Please refer this code to resolve your problem.
Suppose
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
print 3 in list2
Output:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
True
Just realized OP wants to check A string only
You can define a function and match the string in a list recursively like this:
def plist(lst, n):
# loop inside the list
for each in lst:
# if "each" is also a list (nested), check inside that list, too
if isinstance(each, list):
# this will reuse your "plist" and loop over any nested list again
plist(each, n)
# if n matches any element in the list, return True
if any(n in each_letter for each_letter in each):
return True
# if after looping over your list + nested list, return False if no match is find
else:
return False
>> lst = ['o', ['hello', 'c', 'bye']]
>> plist(lst, 'o')
>> True
>> plist(lst, 'h')
>> True
>> plist(lst, 'z')
>> False
Hope this solves your problem.
Here is your error
def find_letter(lst): # You receive your list as lst
lst=['o','hello', 1] # Opppsss! You override it. It does not matter what you receive with lst above, now its value is ['o','hello', 1]
n='o'
So in find_letter(lst[0:])
, you use list slicing, but on lst=['o','hello', 1]
line, you override it again and you always execute your search on the first element of the list.
n = "o" # you can set this too, but this is optional
def find_letter(lst):
# do not set a value to lst in here
if not lst:
return 0
elif lst[0] == n: # You checked first element in here
return True
elif find_letter(lst[1:]): # since you checked the first element, skip it and return the orher elements of the list
return True
else:
return False
lst = ['o','hello', 1]
print find_letter(lst)
Since you need a recursive version:
Short version
def find_letter(let, lst):
return (lst or False) and
((isinstance(lst[0], str) and let in lst[0]) or find_letter(let, lst[1:]))
More explicit version
def find_letter(let, lst):
if lst:
e = lst[0]
return (isinstance(e, str) and let in e) or find_letter(let, lst[1:])
return False
Even more explicit version
def find_letter(let, lst):
if lst:
e = lst[0]
if isinstance(e, str) and let in e:
return True
return find_letter(let, lst[1:])
return False
Note that I leave out a couple of else:
because they are not necessary after a return
statement. If you don’t want to test for a letter in a string, but just for equality, replace let in ...
by let == ...
.
Here is a one line lambda:
any(list(map(lambda x: True if n in str(x) else False,lst )))
data:
lst=['o','hello', 1]
n='o'
output 1:
True
note:
any()
checks if any True
, then True
– otherwise False
– so without the any()
we get:
list(map(lambda x: True if n in str(x) else False,lst ))
output 2:
[True, True, False]