Iterate through 2 Python list and get all x to y combinations

Viewed 230

I have the following two lists:

x = [1,2] y = [4,5,6]

I want to iterate x by z.

I have a variable called code set to NONE and another variable called value also set to NONE. Here is the output I am aiming for:

1st iteration, code = 1 and value = 4
2nd iteration, code = 1 and value = 5
3rd iteration, code = 1 and value = 6
4th iteration, code = 2 and value = 4
5th iteration, code = 2 and value = 5
6th iteration, code = 2 and value = 6

Here is what I have tried:

x = [1, 2]
y = [4, 5, 6]

code = None
value = None


for x_ids, y_ids in zip(x, y):
    code = x_ids
    value = y_ids
    print("c", code)
    print("v", value)

output: 
c 1
v 4
c 2
v 5

Can anyone suggest how to get the output described above?

1 Answers

This is one way to achieve what you're looking for:

x = [1, 2]
y = [4, 5, 6]

code = None
value = None

iter_count = 0
for x_ids in x:
    code = x_ids
    for y_ids in y:
        iter_count += 1
        value = y_ids
        print('{} iteration, code = {} and value = {}'.format(iter_count, code, value))
        #print(str(iter_count) + ' iteration, code = ' + str(code) + 'and value = ' + str(value))

Like discussed in the comments, this code iterates through all elements of y for every element in x. In your original code, you were iterating through both lists all at ones, using zip. Since you want to print the number of iteration too, there is a new variable, iter_count, that counts and stores those.

The code has two print statements, they print the same messages. The commented out one concatenates strings, and numbers converted to strings. The uncommented one may be less intuitive but it is often more useful and cleaner. It's worth looking at it, you can find an introduction here.

Last thing, if you need that too - to print numbers in 1st, 2nd etc. format you can use some of these approaches.

Related