Montague27 Montague27 - 3 months ago 13
Python Question

Python generate and return tuples in a non-list form

def tuple_gen(x, y, num):
pos = []
for i in range(num):
x += 1
pos.append([x, y])
pos[i] = tuple(pos[i])
return pos


my input is:

>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]


What I want is to return tuples but not a list:

>>> tuple_gen(0,1,5)
(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)


Because I want to form a list that includes different kind of tuples:

>>> [tuple_gen(0,1,5), tuple_gen(0,2,6)]
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]


I want a short and clearest solution.

*note that I don't want to use any
extend
or
append
to merge those lists because I need so many tuples

Answer

You are currently returning a list of tuples:

>>> tuple_gen(0,1,5)
[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]

You could return a tuple of tuples with return tuple(pos).

That is what you asked for, but it won't help you for this use case:

[tuple_gen(0,1,5), tuple_gen(0,2,6)]

That will still be a list of two tuples of tuples.

What you really need is to return a list, as you do, and then concatenate those lists later:

tuple_gen(0,1,5) + tuple_gen(0,2,6)