Python : List Comprehensn with IF/ELSE statement

Question:

I’m looking for an oneliner for this below logic:

links (list) variable will contain = ['**www.google.com/api/1.js**','**/path.js**']
url = "mysite.com"
valid_links = [url + u for u in links if not urlparse(u).netloc ]

This will give me only [‘mysite.com/path.js’] but not ‘www.google.com‘ in the list. I need full urls as it is and paths appended with my own url.

So i added else block:

url = "mysite.com"
valid_links = [url + u for u in links if not urlparse(u).netloc else u]

Can someone help me to get rid of the syntax error for this oneliner.

I tried it with

for #[iter]
   if:
      ....
      append to list
   else:
      ....
      append to list

But i want understand how to convert it in a oneliner

Asked By: Sunil Raj

||

Answers:

I’m looking for an oneliner.

Here is it:

from urllib.parse import urlparse
links = ['**www.google.com/api/1.js**','**/path.js**']
url = "mysite.com"
valid_links = [ url+'/'+u for u in links if not urlparse(u).netloc]
print(valid_links)

and if you want to implement if/else the right syntax would be:

valid_links = [url+'/'+u if not urlparse(u).netloc else u for u in links]

both variants printing in case of the given list:

['mysite.com/**www.google.com/api/1.js**', 'mysite.com/**/path.js**']

Notice that:

The provided if/else expression works anywhere.
I use it often in assignments like for example:

x = 2 if y==3 else 1

It sets x to 2 if the variable y has the value 3 and if not it sets x to 1.

The if in the list comprehension is an item selection filter and an else does not make any sense there.

In other words the if/else expression has nothing to do with the list comprehension as such. You don’t want to skip any items from the list (this is the purpose of a final if or multiple ifs in list comprehension). You want the resulting item value to be another one depending on a condition.

See Ternary conditional operator in Python (Wikipedia)

Answered By: Claudio