peperunas
peperunas

Reputation: 438

Python - Best method to create list made of variables

I made this chunk of code but I think this isn't the "best" out there... how can I create a list made of other variables?

track_data = []
track_data.append(track['title'][0])
track_data.append(track['artist'][0])
track_data.append(track['album'][0])
return track_data

I tried to to do

track_data = [track['title'][0], track['artist'][0], track['album'][0]]

but it didn't appear as a good solution for my IDE (PyCharm).

What should I use?

Upvotes: 1

Views: 91

Answers (2)

oxfn
oxfn

Reputation: 6840

Here is what I do when I want to remember the Awesomeness of Python

track_data = [track[prop][0] for prop in ('title', 'artist', 'album')]

Upvotes: 3

ndpu
ndpu

Reputation: 22561

fields = ['title', 'artist', 'album']
track_data = [track[f][0] for f in fields]

Upvotes: 2

Related Questions