2

I have 2 lists

Numberset1 = [10,11,12]
Numberset2 = [1,2,3,4,5]

and i want to display output by manipulating the lists, the expected output is

10 1
10 2
10 3
10 4
10 5
11 2
11 3
11 4
11 5
11 1
12 3
12 4
12 5
12 1
12 2

Since the 2nd number in first list should start from the second number from the second list i tried enumerating it and created another list

test=[j for i, o in enumerate(Numberset2) for j in Numberset2[i:] + Numberset2[:i] ]

The code i have tried is as follows

Numberset1 = [10,11,12]
Numberset2 = [1,2,3,4,5]
test=[j for i, o in enumerate(Numberset2) for j in Numberset2[i:] + Numberset2[:i] ]
for D in Numberset1:
    for j in test:
        print(D,j)

The output i am getting is

10 1
10 2
10 3
10 4
10 5
10 2
10 3
10 4
10 5
10 1
10 3
10 4
10 5
10 1
10 2
10 4
10 5
10 1
10 2
10 3
10 5
10 1
10 2
10 3
10 4
11 1
11 2
11 3
11 4
11 5
11 2
11 3
11 4
11 5
11 1
11 3
11 4
11 5
11 1
11 2
11 4
11 5
11 1
11 2
11 3
11 5
11 1
11 2
11 3
11 4
12 1
12 2
12 3
12 4
12 5
12 2
12 3
12 4
12 5
12 1
12 3
12 4
12 5
12 1
12 2
12 4
12 5
12 1
12 2
12 3
12 5
12 1
12 2
12 3
12 4

I know that i am iterating the test and that is why i am getting these many numbers, how can i make sure that i am getting only the expected output

Python_newbie
  • 203
  • 2
  • 9

2 Answers2

7

Just print in a double loop using shifted indices and modulo:

Numberset1 = [10,11,12]
Numberset2 = [1,2,3,4,5]

for i,n in enumerate(Numberset1):
    for j in range(len(Numberset2)):
        print(n,Numberset2[(j+i) % len(Numberset2)])

result:

10 1
10 2
10 3
10 4
10 5
11 2
11 3
11 4
11 5
11 1
12 3
12 4
12 5
12 1
12 2

or generate the tuples using list comprehension:

[(n,Numberset2[(j+i) % len(Numberset2)]) for i,n in enumerate(Numberset1) for j in range(len(Numberset2))]

which gives:

[(10, 1), (10, 2), (10, 3), (10, 4), (10, 5), (11, 2), (11, 3),
 (11, 4), (11, 5), (11, 1), (12, 3), (12, 4), (12, 5), (12, 1), (12, 2)]

how it works:

Numberset2[(j+i) % len(Numberset2)] is accessing the jth index of Numberset, with, added the offset of the outer bound (0, 1, ... etc...)

If we leave j+i it reaches len(Numberset2) and we get array out of bounds exception. To make sure that index is shifted and remains in range, we add a modulo operator so it wraps around.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

Given:

Numberset1 = [10,11,12]
Numberset2 = [1,2,3,4,5]

You can make an infinite looping iterator over Numberset2 using itertools.cycle take a slice of the iterator using itertools.islice and skip one after each loop using next():

from itertools import cycle, islice

it = cycle(Numberset2)
for i in Numberset1:
    for j in islice(it, len(Numberset2)):
        print(i, j)
    skipped1 = next(it)
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119