# Create an infinite set with list comprehension

Hello. In Sage is possible to create B = Set(Primes()). For B Sage says Set of all prime numbers: 2, 3, 5, 7, ... . So B is infinite. I try to create now a set C = Set([x^2 for x in QQ]). I am expecting to get something similar like above, but Sage does not get so far. After some 20 Minutes of waiting I broke down the action. Is possible to create an infinite Set with list comprehension? I know that lists should befinite but the notation used by list comprehension is very near on the mathematical way to describe a set like D = Set([x^2 for x in range(10)]) for example. Any help appreciated. Thank you and regards, Vasile

edit retag close merge delete

Sort by ยป oldest newest most voted

The input

Set([x^2 for x in QQ])


makes Sage first try to evaluate [x^2 for x in QQ], but that is an infinite list, so Sage will never complete that step, it will just fill up memory.

B = (x^2 for x in QQ)


which is an iterator which can output one by one the squares of rational numbers, but never tries to compute them all at once.

If the reason you were using Set was to avoid duplicates, in this example you can just require x nonnegative:

B = (x^2 for x in QQ if x >= 0)


so that you get each square of a rational only once.

You can then get the first few terms by

sage: [B.next() for _ in xrange(10)]
[0, 1, 1/4, 4, 1/9, 9, 4/9, 9/4, 1/16, 16]


See the thematic tutorial on comprehensions, iterators and iterables for more on that theme.

more

Hello, thank you for the answer. The reason for using Set was, that I wanted to operate with Sage sets. I wanted to do some set theory operations like union or difference of two sets. I thought the members of an operation like A = Set(B.difference(C)) should be all the same type. Thank you. Vasile

( 2014-07-21 15:30:52 +0200 )edit

Another remark: a 'generator' object has no attribute 'cardinality'. So if I want to work with this, I am getting the error "'generator' object has no attribute 'cardinality'". This was another reason I wanted to work with sets.

( 2014-07-21 15:35:27 +0200 )edit