For loop issues

Hi ,
I wanted to join two lists using a loop.
Ex:
[‘10.180.0.73’, ‘10.180.0.168’]
[‘eu-de-1a’, ‘eu-de-1b’]

something like this.
10.180.0.73_eu-de-1a
10.180.0.168_eu-de-1b

I tried this it didn’t help me:

for i in ip1:
for i2 in az:
print(i,i2)

it loops everything duplicate entries I get…

Could you please help me with that…

That prints every element in az for the first element of ip1, then again
for the second element and so on.

instead, you want to gather the matching elements from each list.

For example:

for i in range(len(ip1)):
    print(i, ip1[i], az[i])

Then you could do as you like with each pair of elements.

Also, Python has a zip() builting function:

print(list(zip(ip1,az)))
for ip, region in zip(ip1, az):
    print(ip, region)

Cheers,
Cameron Simpson cs@cskk.id.au

If you wanted to do it manually, you’d probably want to use enumerate() or somehow keep track of the index of each list. Then in a single loop you’d access the same index in each list.

But you have zip() to pull in the corresponding elements from both lists so you don’t have to index it yourself.

ips = ["10.180.0.73", "10.180.0.168"]
names = ["eu-de-1a", "eu-de-1b"]

for ip, name in zip(ips, names):
    print(f"{ip}_{name}")
10.180.0.73_eu-de-1a
10.180.0.168_eu-de-1b

Thank you it worked :slight_smile:

Thank you :slight_smile: