Los
Los

Reputation: 67

How can I put this DRY code into a for loop?

I am formatting a legend in pyplot, and have successfully gotten the output I want. However, I'm trying to figure out how to format this code into a for loop.


This is the code I am trying to loop:

L.get_texts()[0].set_text('Global')
L.get_texts()[1].set_text('Bangkok')
L.get_texts()[2].set_text('NYC')
L.get_texts()[3].set_text('Perth')
L.get_texts()[4].set_text('Quito')
L.get_texts()[5].set_text('Santiago')
L.get_texts()[6].set_text('Singapore')
L.get_texts()[7].set_text('Tianjin')

I can loop for each index[0,7], but I can't figure out how to loop for the set_text('argument') as well. This is what I have tried so far:

legend_labels = ['Global', 'Bangkok', 'NYC', 'Perth', 'Quito', 'Santiago', 
'Singapore', 'Tianjin']

for i in range(8):
L.get_texts()[i].set_text(legend_labels)

I made the list, legend_labels, that I want to loop through. I've tried a few different nested for loops, but can't seem to get it working.

From the code that I am trying now this is the output I get: Notice only 'Tianjin' gets printed on the legend.

This is my desired output: Each item in list is printed on the legend.

Upvotes: 2

Views: 47

Answers (3)

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

legend_labels = ['Global',
                 'Bangkok',
                 'NYC',
                 'Perth',
                 'Quito',
                 'Santiago',
                 'Singapore',
                 'Tianjin'
                 ]

for i in range(8):
    L.get_texts()[i].set_text(legend_labels[i])

Upvotes: 0

JohanC
JohanC

Reputation: 80449

You'd need to assign the i'th label to the i't text:

for i in range(8):
    L.get_texts()[i].set_text(legend_labels[i])

More pythonic would be

for text, label in zip(L.get_texts(), legend_labels):
    text.set_text(label)

Upvotes: 2

Sheldore
Sheldore

Reputation: 39072

You can use enumerate that will give you both, the index i as well as the label

for i, label in enumerate(legend_labels):
    L.get_texts()[i].set_text(label)

Upvotes: 3

Related Questions