10

Possible Duplicate:
Initialize list with same bool value

I'm attempting to make a prime number generator in python 2.7 and plan to use an array (or list) of booleans which will indicate whether a given number is prime.

Let's say I wanted to initialize a list of 5000 booleans, how would I do so without having to manually type [True, True, ...]

flau
  • 1,328
  • 1
  • 20
  • 36
  • 1
    See this post - http://stackoverflow.com/a/13382804/1679863 – Rohit Jain Dec 07 '12 at 22:26
  • 1
    For such a big list, it is probably worth using a Numpy array - `np.repeat([True], 5000)` uses three orders of magnitude less memory than `[True] * 5000`. – lvc Dec 07 '12 at 23:00
  • 1
    For large numerical problems, bytearray is the better choice: http://stackoverflow.com/a/42445940/74291 – Waylon Flinn Feb 24 '17 at 18:36

2 Answers2

24

You could try this:

[True] * 5000

Lists can be multiplied in Python (as can strings):

>>> [True] * 3
[True, True, True]
>>> "abc" * 3
'abcabcabc'
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 6
    Just as a side note: This works well for lists of primitive types, such as numbers and booleans, but not for lists of objects (or lists of lists, lists or dicts, etc.), as in this case the list will contain 5000 times _the same_ instance. – tobias_k Dec 07 '12 at 22:44
  • thanks, that comes handy – Kunal Vyas May 02 '14 at 20:17
0

I'm attempting to make a prime number generator in python 2.7 and plan to use an array (or list) of booleans which will indicate whether a given number is prime.

This sounds really wasteful. A better approach would be to have a set() with only the numbers you need:

>>> primes = {2, 3, 5, 7}
>>> 4 in primes
False
>>> 5 in primes
True
lqc
  • 7,434
  • 1
  • 25
  • 25
  • 5
    So you suggest him to manually type {2, 3, 5, 7 ...} instead of [True, True, True ...]. Interesting approach. – kaspersky Dec 07 '12 at 22:37
  • 1
    Because there was a downvote I have to say I heartfully agree! The distance between 2 primes becomes increasingly larger, so the bigger you go the more wasteful `false` elements you have. – erikbstack Dec 07 '12 at 22:38
  • +1 this would of course be a better approach. – Rohit Jain Dec 07 '12 at 22:40
  • @gg.kaspersky No I'm giving an example use for a `set()` (hint: it's a function!). If someone says that they're writing a generator I assume they know it won't come down to calculating them on paper and typing into the program. – lqc Dec 07 '12 at 22:44
  • I'm not saying using a set is not a better option, I just pointed out he didn't answer the question. – kaspersky Dec 07 '12 at 22:46
  • 6
    @lqc, the OP probably wants to implement the Sieve of Eratosthenes algorithm, which is based on that list initialization. You actually suggest him to implement a different algorithm. – kaspersky Dec 07 '12 at 22:50