Reply to comment

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.

Reply

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.