Sang Nguyen
Sang Nguyen

Reputation: 33

Set Comprehensions in Python

I came across this code and didn't quite really understand it:

s = { i*j for i in range(10) for j in range(10)}
print(s)

The result is {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, 28, 30, 32, 35, 36, 40, 42, 45, 48, 49, 54, 56, 63, 64, 72, 81}

As far as I'm concerned, it should iterate over the list of "i" and "j", respectively. For example, if "i" equals 0, j would go from 0 to 9, and the first elements of set s will be {0, 0, 0, ...} and the same for "i" equals 1, 2, 3,...

Could anyone help me shed more light on this?

Upvotes: 0

Views: 130

Answers (3)

Chris
Chris

Reputation: 36476

It is equivalent to:

s = set()

for i in range(10):
  for j in range(10):
    s.add(i * j)

print(s)

This iterates 100 times.

To see the combinations you might try:

{(i, j) for i in range(10) for j in range(10)}
# {(7, 3), (6, 9), (0, 7), (1, 6), (3, 7), 
#  (2, 5), (8, 5), (5, 8), (4, 0), (9, 0),
#  (6, 7), (5, 5), (7, 6), (0, 4), (1, 1), 
#  (3, 2), (2, 6), (8, 2), (4, 5), (9, 3),
#  (6, 0), (7, 5), (0, 1), (3, 1), (9, 9),
#  (7, 8), (2, 1), (8, 9), (9, 4), (5, 1),
#  (7, 2), (1, 5), (3, 6), (2, 2), (8, 6),
#  (4, 1), (9, 7), (6, 4), (5, 4), (7, 1),
#  (0, 5), (1, 0), (0, 8), (3, 5), (2, 7),
#  (8, 3), (4, 6), (9, 2), (6, 1), (5, 7),
#  (7, 4), (0, 2), (1, 3), (4, 8), (3, 0),
#  (2, 8), (9, 8), (8, 0), (6, 2), (5, 0),
#  (1, 4), (3, 9), (2, 3), (1, 9), (8, 7),
#  (4, 2), (9, 6), (6, 5), (5, 3), (7, 0),
#  (6, 8), (0, 6), (1, 7), (0, 9), (3, 4),
#  (2, 4), (8, 4), (5, 9), (4, 7), (9, 1),
#  (6, 6), (5, 6), (7, 7), (0, 3), (1, 2),
#  (4, 9), (3, 3), (2, 9), (8, 1), (4, 4),
#  (6, 3), (0, 0), (7, 9), (3, 8), (2, 0),
#  (1, 8), (8, 8), (4, 3), (9, 5), (5, 2)}

Note: order is not guaranteed in a set.

Should you wish to see all of the multiples, use a list comprehension which does preserve order.

[i * j for i in range(10) for j in range(10)]

Upvotes: 0

Logan Tischler
Logan Tischler

Reputation: 115

You're using a set (or dictionary), which behaves differently than a list. The result you're expecting should use square brackets instead of curly brackets.

s = [i*j for i in range(10) for j in range(10)]
print(s)

# Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 0, 9, 18, 27, 36, 45, 54, 63, 72, 81]

Upvotes: -1

Rahul K P
Rahul K P

Reputation: 16081

Since it's a set it won't hold duplicate values. That's why it doesn't have all the values.

There is no such case as set {0, 0, 0, ...}.

In [1]: {0, 0, 0, 0}
Out[1]: {0}

if you need whole values you have to use list comprehension.

s = [ i*j for i in range(10) for j in range(10)]

Upvotes: 1

Related Questions