2
[k for k in range (1,42) if k%2 != 0]

output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41]

Now, I want to make it to:

[-1, 3, -5, 7, -9, 11, -13, 15, -17, 19, -21, 23, -25, 27, -29, 31, -33, 35, -37, 39, -41]

So I tried:

def test(N):
    k = []
    for i in range (1,N+1):
        if(i%2 != 0):
            k.append(i)
    for b in k[::2]:       <--- it changes the value but doesn't update the list
        b = -b
    return k
test(43)

Any ideas or suggestions on how to approach this problem? Or the other question is, how could I traverse the even numbered index in the list while updating the element to a negative value

misheekoh
  • 450
  • 3
  • 17

3 Answers3

2

This works:

numbers = (k for k in range(1, 42) if k%2 != 0)
[x * [-1, 1][n % 2] for n, x in enumerate(numbers)]

Output:

[-1, 3, -5, 7, -9, 11, -13, 15, -17, 19, -21, 23, -25, 27, -29, 31, -33, 35, -37, 39, -41]

Performance

The approach using modulo is a bit faster than the one for alternating series as suggest by Malik Brahimi in a comment:

%%timeit
numbers = (k for k in range(1, 420000) if k%2 != 0)
[x * (-1)**(n + 1) for n, x in enumerate(numbers)]
1 loops, best of 3: 263 ms per loop

%%timeit
numbers = (k for k in range(1, 420000) if k%2 != 0)
[x * [-1, 1][n % 2] for n, x in enumerate(numbers)]
1 loops, best of 3: 210 ms per loop
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
1
[k if k%4==3 else -k for k in range (1,42) if k%2 != 0]
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

b is a reference to the (immutable) integer stored in k. By updating b to equal -b, you're not modifying the list, you're simply changing the thing that b referecnes, for the int 2 object to the int -2 object. You might be better off just doing the negation as you build the list:

def test(N):
    k = []
    for i in range (1,N+1, 2): # i increases in steps of 2
        if i % 4 == 1:
            i = -i
        k.append(i)
    return k

test(43)
Tom Dalton
  • 6,122
  • 24
  • 35