Chung
Chung

Reputation: 247

creating sets of tuples in python

How do i create a set of tuples with each tuple containing two elements? Each tuple will have an x and y value: (x,y) I have the numbers 1 through 50, and want to assign x to all values 1 through 50 and y also 1 through 50.

S = {(1,1),(1,2),(1,3),(1,4)...(1,50),(2,1)......(50,50)}

I tried

positive = set(tuple(x,y) for x in range(1,51) for y in range(1,51))

but the error message says that a tuple only takes in one parameter. What do I need to do to set up a list of tuples?

Upvotes: 24

Views: 106884

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113915

mySet = set(itertools.product(range(1,51), repeat=2))

OR

mySet = set((x,y) for x in range(1,51) for y in range(1,51))

Upvotes: 24

senshin
senshin

Reputation: 10350

tuple accepts only one argument. Just explicitly write in the tuple instead using parentheses.

#                  vvvvv
>>> positive = set((x,y) for x in range(1,5) for y in range(1,5))
>>> positive
{(1, 2), (3, 2), (1, 3), (3, 3), (4, 1), (3, 1), (4, 4), (2, 1), (2, 4), (2, 3), (1, 4), (4, 3), (2, 2), (4, 2), (3, 4), (1, 1)}

Upvotes: 7

Related Questions