1

In Python I have this statement:

blog_ids = [c.blog_id for c in connections]

Which basically tells Python to create an array of all the blog IDs in the connections. Unfortunately, if the connections object has some None types, c.blog_id would cause an exception. Is there any syntax to solve this problem? I tried this but it doesn't work:

blog_ids = [c.blog_id for c not None in connections]

2 Answers 2

8
blog_ids = [c.blog_id for c in connections if c is not None]
Sign up to request clarification or add additional context in comments.

3 Comments

Which could be shortened to [c.blog_id for c in connections if c] if you know connections only has None or valid values.
Thanks. But what is the syntax for these kind of statements? Are they just special syntax for the 'for' and 'if' statements? In the words, can we form more complicated statements based on some syntax?
Here you have some tutorial on list comprehensions: docs.python.org/howto/…
0

The thing here probably is to ask what kind of objects you have in your connections object. Are they either valid objects with blog_id attribute or None objects. Or is there possibility that among those objects there are also some other objects (in addition to None objects) without blog_id attribute.

1 Comment

That's a good point, but yes, they are either valid objects with blog_id attribute, or None objects. Actually, they are returned via a Google AppEngine statement for the Connection class, so they are either valid, of None if some key is invalid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.