kongehund
kongehund

Reputation: 25

Python: Removing unnecessary brackets?

I wrote a very simple function in Python, that prints out all prime numbers within a specific sequence.

It works fine, but the results it gives me have way too many brackets/parentheses in them. I'd like to get the result as one output with a single list including all of the numbers, rather than a lot of outputs, each containing a single number.

Here's the code:

def prime_list(X, Y):
    Z = 0
    while X <= Y:
        if is_prime(X):
            Z = Z, X
        X = X + 1
    print (Z)

The function is_prime() used in the code simply returns True, if the number is a prime number, and False, if it isn't.

Basically, for every loop, it checks if X is a prime number. If it is, X will be added to the list called Z. Although, when it does this, it also adds unnecessary brackets/parentheses to the list. Here's the result, using the sequence 1-100:

>>> prime_list(1,100)
(((((((((((((((((((((((((0, 2), 3), 5), 7), 11), 13), 17), 19), 23), 29), 31), 37), 41), 43), 47), 53), 59), 61), 67), 71), 73), 79), 83), 89), 97)

As you can see, there are way too many brackets/parentheses.

How can I rewrite the code, so it doesn't make these?

Upvotes: 2

Views: 1986

Answers (4)

Robert Nix
Robert Nix

Reputation: 69

In the line "z = z, x", what you've done is to assign to z a list containing z and x. After the first time, z is always a list when you arrive here, so you get a new list, containing the old list, and an integer. So, z = 0 at the start, then 0, 1 next, and then it goes oval... The next time, it becomes (0, 1), 2; the previous list (the old z), and the new x. Next time, you get ((0, 1), 2), 3, and so on.

If you use z.append(x), it adds an additional item to the list, rather than creating a new, 2 element list each time. Using z.append(x), in the end, you'll get (0, 1, 2, 3, ...), which is closer to what you'd thought you'd get.

Upvotes: 0

janos
janos

Reputation: 124646

You can also concatenate tuples (notice the trailing comma when appending to Z):

def prime_list(X, Y):
    Z = ()
    while X <= Y:
        if is_prime(X):
            Z += X,
        X = X + 1
    print (Z)

Not sure which is more efficient: appending to a list or concatenating tuples...

Upvotes: 0

Jo So
Jo So

Reputation: 26501

Not a direct answer, but here's a cleaner and shorter way:

def prime_list(X, Y):
    return [ x for x in range(X, Y+1) if is_prime(x) ]

Upvotes: 3

Cairnarvon
Cairnarvon

Reputation: 27762

Just append to a list instead of nesting tuples:

def prime_list(X, Y):
    Z = []
    while X <= Y:
        if is_prime(X):
            Z.append(X)
        X = X + 1
    return Z

Upvotes: 5

Related Questions