Anjith
Anjith

Reputation: 2308

Multiple if conditions in a list comprehension

I have a list with links and was trying to filter those and got stuck. I was able to write a function for multiple if statements explicitly but was looking to write it directly in the list comprehension.

I have tried multiple ways (i.startswith(), "https" in i) to write it but couldn't figure it out.

This is the list comprehension:

[i.a.get('href') for i in link_data if i != None]

Output:

['/gp/redirect.html/ref=as',
'https://www.google.com/',
'https://www.amazon.com/',
'/gp/redirect.html/ref=gf']

I only require links which starts with https.

How can I write this if condition in my list comprehension given above? Any help is appreciated.

Upvotes: 0

Views: 66

Answers (1)

anthony sottile
anthony sottile

Reputation: 69844

You can combine two conditionals with and -- but list comprehensions also support multiple ifs (which get evaluated with and)

Here's two options for what you want:

# combining conditions with `and`
output = [
    i.a.get('href') for i in link_data
    if i is not None and i.a.get('href').startswith('https')
]

# combining conditions with multiple `if`s
output = [
    i.a.get('href') for i in link_data
    if i is not None
    if i.a.get('href').startswith('https')
]

(note these were indented for clarity, the whitespace between the [ and ] is not important)

Upvotes: 1

Related Questions