Machi
Machi

Reputation: 131

python nested for loop iteration

I would like the inner for loop to give me one value and goes on to the next iteration for each outer loop. Appreciate your responds.

Currently the result:

Result should just be:

Upvotes: 1

Views: 119

Answers (3)

Azsgy
Azsgy

Reputation: 3317

Use zip to iterate over two objects at the same time.

note: you are using sets (created using {"set", "values"}) here. Sets have no order, so you should use lists (created using ["list", "values"]) instead.

for key, value in zip(employees, excel):
    print(key, value)

Upvotes: 5

wohe1
wohe1

Reputation: 775

First of all, use square brackets [] instead of curly brackets {}. Then you could use zip() (see other answers) or use something very basic like this:

for i in range(len(employees)):
    print(employees[i], excel[i])

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

You can use zip after changing the type of your input data. Sets order their original content, thus producing incorrect pairings:

employees=['ID #','Personal Name','Emergency contact']
excel=['123456', 'John','Peter']
new_data = [a+b for a, b in zip(employees, excel)]

Output:

['ID #123456', 'Personal NameJohn', 'Emergency contactPeter']

Upvotes: 2

Related Questions