Snake_Byte #37: Traversing Data with List Comprehensions

In a previous blog post, we covered list comprehensions to generate a dataset. In this post, I'll be covering how to simplify traversing a dataset to pull specific data using list comprehensions.

Let's start with a nested list of objects like this:

Say you only want to pull the relevant songs that are by 'Artist 2'. The long form way to do this would be:

But there's a simpler way, only using one line and list comprehensions:

Now let's say you only want to return one parameter, rather than the whole object, just add a get and it'll return an array of those params:

Now let's say you want to prepend a string onto each returned title, you can add a function to do that as well and include it in the list comprehension:

Hopefully this helps simplify your data traversing. For more information, here's the official Python page on list compehensions: