Dane Brouwer
Dane Brouwer

Reputation: 2972

Condensing an if-statement

I have the following lists:

languages =["java", "haskell", "Go", "Python"]
animals = ["pigeon", "python", "shark"]
names = ["Johan","Frank", "Sarah"]

I want to find out whether or not python exists in all three of the following lists. The following if-statement is what I came up with just using the "in" method and "and" operators.

if("Python" in languages and "Python" in animals and "Python" in names )

Is there a way to condense this statement into a smaller length?
I.E.

if("Python" in languages and in animals and in names)

Upvotes: 1

Views: 236

Answers (6)

9000
9000

Reputation: 40894

Consider:

if all("Python" in x for x in (languages, animals, names)): 

Upvotes: 4

Chris
Chris

Reputation: 22963

If you are using Python 3, you can use extended iterable unpacking:

if 'Python' in (*languages, *animals, *names):

Upvotes: 2

Andrew
Andrew

Reputation: 669

Short answer: No, the language syntax does not allow this.

If you really want to cut down on duplicating 'Python', you could use something like this in your if condition:

all('Python' in p for p in (languages, animal, names))

I also suggest that maybe you could reevaluate the design to make your code more flexible. Comprehensions and generator expressions are a good start.

Upvotes: 0

jasonharper
jasonharper

Reputation: 9597

If this is a test you're expecting to do repeatedly, it would be more efficient to pre-calculate the intersection of your lists:

lanimes = set(languages) & set(animals) & set(names)

if "Python" in lanimes:

(The in operator is O(n) for a list, O(1) for a set.)

Upvotes: 5

Camden Cheek
Camden Cheek

Reputation: 65

I don't think Python has any syntax sugar specifically like that, but depending on how many lists you have, you could do something like

if all("Python" in x for x in [languages, animals, names])

On its own, it's probably a bit more verbose than your ands, but if you have a large number of lists, or you already have a list of lists, then it should save some space, and IMHO it is more immediately clear what the goal of the if statement is.

Upvotes: 2

Dan D.
Dan D.

Reputation: 74655

You can avoid repeating "Python":

if all("Python" in L for L in [languages, animals, names]):

But this is not much shorter.

Upvotes: 6

Related Questions