Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get first element from a list without exception

Consider this code

description = ""
desc = hxs.select('/html/head/meta[2]/@content').extract()
if len(desc) > 0:
    description = desc[0]       
item["description"] = description

desc is a list of strings. If list is empty description is an empty string, if not it's the first elements from the list. How to make it more pythonic?

Forgot to mention that I have to use 2.7

like image 680
Lukasz Madon Avatar asked Jul 10 '13 17:07

Lukasz Madon


3 Answers

You can write:

desc = hxs.select("/html/head/meta[2]/@content").extract()
item["description"] = desc[0] if len(desc) > 0 else ""

As pointed out in the comments below, you can also directly evaluate the list in a boolean context:

item["description"] = desc[0] if desc else ""
like image 181
Frédéric Hamidi Avatar answered Sep 20 '22 22:09

Frédéric Hamidi


Alternately you could use make use of the fact that next supports a default

item["description"]  = next(iter(desc), "")
like image 25
iruvar Avatar answered Sep 21 '22 22:09

iruvar


You can use exception handling (although it's more verbose than using the conditional expression).

desc = hxs.select('/html/head/meta[2]/@content').extract()
try:
    description = desc[0]
except IndexError:
    description = ""
like image 30
chepner Avatar answered Sep 20 '22 22:09

chepner