Search code examples
pythonpython-3.xlistenumerate

Why x variable is created and what is the logic used in this code


names = [ "Rachael Green", "Goodfellow Ian", "Tedd Crock", "Mina Joseph"]
salaries = [10260 , 41571 , 71211 , 52141 , 35781]
people_salaries = []
 
for i , j in enumerate(names):
    x = j + " $" + str(salaries[i])
    people_salaries.append(x)

Solution

  • The variable x is created here to create a temporary string that will be appended to a list. Enumerate will create a tuple with a number like an index paired with every item iterated (thst is why the loop expects 2 values (i,j). Then, the code will take the enumerate number and use it as an index for salaries.

    I would recommend 1. creating a Dictionary with the names and salaries and 2. you don't need x for the code, just do people_salaries.append( j + '$' + str(salaries[i]))

    Change the for loop instead of enumerate to for i in salaries or simply with the dictionary method

    for i in people_dict.keys()
    

    and then append with

    people_salaries.append(i + '$' + str(people_dict[i]))