Home > Software engineering >  Create a list of tuples with the first position fixed
Create a list of tuples with the first position fixed

Time:03-23

I'm trying to create a list of tuples with two elements keeping the first item always fixed. This is the code I'm using to achieve this, but it is not working as expected.

def grouper(n, iterable):
    args = [iter(iterable)] * n
    return zip(*args)

df_rel_inward['list_of_tuples'] = ''

for i in range(0,len(df_rel_inward['tuple']), 1):
    df_rel_inward['list_of_tuples'][i] = tuple(grouper(2, df_rel_inward['tuple'][i]))

df_rel_inward

The output is ((1, 2), (3, 4), (5, 6))

I have no idea on how to fix the first element, so the output can be ((1, 2), (1, 3), (1, 4), (1, 5), (1, 6))

Can you, please, advise?

CodePudding user response:

This can be helpful:

df_rel_inward = []
for i in range(1, 10):
    df_rel_inward.append((1,i))
print(tuple(df_rel_inward))

CodePudding user response:

You have an indexing problem. When you create a tuple, you index it with a single [] operator, like this:

a = (1, 2)
a[0] == 1
a[1] == 2

But, you have a list of tuples. Therefore, you have two indexes, using two [] operators:

a = [(1, 2), (3, 4)]
a[0] == (1, 2)
a[0][0] == 1
a[0][1] == 2
a[1][0] == 3
a[1][1] == 4

You'll need to have your first index fixed and the second one iterating.

CodePudding user response:

You can use a list comprehension

t = tuple((1,i) for i in range(1,7))
  • Related