Home > Software engineering >  How to use two loop correctly in python
How to use two loop correctly in python

Time:12-23

Hi guys I have problem

This is my code :

services = {
    'first':[],
    'second':[]
}

x = [1,2,3,4,5]
for i in services:
    print('loop-one -  ',i)
    for i in x:
        services['first'].append(i)

print(services)

Output of this code is {'first': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5], 'second': []} If you notice He added twice .

my purpose is something like this , I want add once {'first': [1, 2, 3, 4, 5], 'second': []}

Thanks !

CodePudding user response:

The inner for loop is using the same loop variable i as the outer loop. This means that the value of i is overwritten with each iteration of the inner loop and the final value of i is used to update the services dictionary.

Here is how you can write your code to iterate both indexes correctly:

services = {
    'first':[],
    'second':[]
}

x = [1,2,3,4,5]
for service in services:
    print('loop-one - ', service)
    for i in x:
        services[service].append(i)

print(services)

CodePudding user response:

Your problem here seems to be that in your outer loop you're iterating over the services dictionary. The services dictionary contains two key-value pairs to which you then iterate over the first key-value pair and append the result to the 'first' list key-value pair. May I ask why you don't just do something like this if your desired output is {'first': [1, 2, 3, 4, 5], 'second': []}?

A simpler way to do it using a single for loop is like this you can find documentation on the extend method here https://docs.python.org/3/tutorial/datastructures.html:

for service in services:
    services[service].extend(x)

Is the requirement to have 2 loops? I am just wondering.

If so, you could try this syntax:

for service in services:
    print('loop-one -  ',service)
    for num in x:
        services[service].append(num)

print(services)

I am assuming you are trying to write the data from x array/list and then append that to the first and second lists. I hope this helps

  • Related