How to Use Zip to Manipulate a List of Tuples
Unlock the Power of Zip to Gain more Flexibility over Your Data
Motivation
Let’s assume when analyzing Twitter data, we get a list of tuples, with the first element contains the frequency of the words and the second element contains the words.
We would like to visualize this data with the y-axis the frequency of the words and the x-axis the text
To create the graph above, it might be wise to get a list of Tweets and another list of frequency, with tweet[i]
corresponding to its frequency freq[i]
, then pass the 2 lists to the arguments in Matplotlib.
How could that be done?
First Attempt with List Comprehension
We store the list of tuples above in freq_tweets
. We could use list comprehension to access the first value of each tuple and create the frequency list:
freq = [x[0] for x in freq_tweets]
freq
And do the same thing with the list of tweets
tweet = [x[1] for x in freq_tweets]