-1

Is there anyway to make this into a single statement in python ?

name = 'Customer_Identify'
useless_list = ['id']
# I Want to make the 3 following lines into a single line. It should return True.
for i in useless_list:
    if (i in name.lower()):
        print(True)

I tried with lambda functions but I maybe doing some mistake somewhere. :(

8
  • 2
    you might want a list comprehension like filtered = [i for i in useless_list if i in name.lower()] Commented Aug 19, 2019 at 15:39
  • 3
    Why? It's perfectly readable as it is Commented Aug 19, 2019 at 15:42
  • I suggest that you learn about list comprehensions and generator expressions Commented Aug 19, 2019 at 15:47
  • If you are only going to print, no need to change anything IMO... Commented Aug 19, 2019 at 15:51
  • 1
    Well, that makes all but 1 answer here irrelevant... Try to be more clear in the question which by the way it is still not clear are you trying to print or return... everytime you say something else Commented Aug 19, 2019 at 16:03

4 Answers 4

4

Since the question asked that it should return true. how about this ?

return any(i in name.lower() for i in useless_list)

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure that's the same functionality... Here you return/print one boolean value if any of the values are in name. In the OP, only True is printed for each value that is in name...
@Tomerikoo The comment in the OP's code states it wants to return the value, i just assume the print was used unintentionally perhaps ?
Oh didn't notice that comment and in that case I guess that satisfies the problem. It is indeed a little unclear... Actually, if that is really the intention I guess this is the best answer
3

How about using generator expressions?

print('\n'.join(str(True) for i in useless_list if i in name.lower()))

3 Comments

That's not a list anymore :)
Oh! I see what you mean. Spot on, sir!
Another similar way without the use of join is unpacking with print's extra arguments. Something like: print(*(True for i in useless_list if i in name.lower()), sep='\n')
0
name = 'Customer_Identify'
useless_list = ['id', 'AA']

[print (item in name.lower()) for item in useless_list]

output:

True
False

Comments

0

That's pretty awful, but you can use a list comprehension to actually invoke print:

[print(True) for i in useless_list if i in name.lower()]

Of course, that builds a totally useless list of Nones...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.