Using List Comprehensions in Python to Look at Lists of Objects

List comprehensions are a difficult-to-learn feature of Python that seem unnecessarily terse, but that’s because the examples aren’t that practical. It’s really a powerful tool.

I was using Tweepy to get some tweets from the Twitter API, and it was a LOT of data. You’d think a 140 character string isn’t that big, but Twitter delivers a lot of metadata. It’s around 7K of metadata per tweet.

So, I had 15 tweets in a list, or around 100K worth of __str__ representing dozens of objects. How do you slice that up?

You use dir() to explore the properties of the different objects.

Then, you use list comprehensions to view that data.

To get a list of all the IDs:

[x.id for x in s]

To get a list of authors:

[x.author.name for x in s]

To get a list of tweets:

[x.text for x in s]

In all these examples, s is the list of tweets that Tweepy produced.

You *think* you need some functions to traverse these lists and objects, but you don’t. All you need are these list comprehensions.