Search code examples
python-3.xlistmergezipenumerate

can this list enumerate method be shorter? or more pythonic?


I would like to see if I can make the following code more concise? even shorter? as a way of learning. thanks.
the code in focus is this line:

for i, (x, y) in enumerate(zip (self.labelVariable_list,self.monday_results)): 
    self.labelVariable_list[i].set(self.monday_results[i])

original code:

    for r in range(12):
        self.labelVariable=tk.StringVar()
        self.label = tk.Label(self, textvariable=self.labelVariable, borderwidth=1, relief="solid", width=9, height=1)
        self.label.grid(row=r+1, column=1)
        self.labelVariable_list.append(self.labelVariable)

    self.labelVariable_list[0].set(self.monday_results[0])
    self.labelVariable_list[1].set(self.monday_results[1])
    self.labelVariable_list[2].set(self.monday_results[2])
    self.labelVariable_list[3].set(self.monday_results[3])
    self.labelVariable_list[4].set(self.monday_results[4])
    self.labelVariable_list[5].set(self.monday_results[5])
    self.labelVariable_list[6].set(self.monday_results[6])
    self.labelVariable_list[7].set(self.monday_results[7])
    self.labelVariable_list[8].set(self.monday_results[8])
    self.labelVariable_list[9].set(self.monday_results[9])
    self.labelVariable_list[10].set(self.monday_results[10])
    self.labelVariable_list[11].set(self.monday_results[11])

I made it to:

    for r in range(12):
        self.labelVariable=tk.StringVar()
        self.label = tk.Label(self, textvariable=self.labelVariable, borderwidth=1, relief="solid", width=9, height=1)
        self.label.grid(row=r+1, column=1)
        self.labelVariable_list.append(self.labelVariable)

    for i, (x, y) in enumerate(zip (self.labelVariable_list, self.monday_results)):
        self.labelVariable_list[i].set(self.monday_results[i])

thanks again for your comments.


Solution

  • You can try list comprehension like this:

    [list_1[i].set(list_2[i]) for i, (l1, l2) in enumerate(zip(list_1, list_2))]