How to add 1 for evens in Python?

Question:

I’m coming from C++.

Intuitively, in C++, here is what I’d do:

int someArray[n];
for (int i = 1 ; i < n ; i++){
   someArray[i] = !(i%2);
}

where i%2 == 0 when i is even and i%2 == 1 when i is odd.

The ! then makes that evens are evaluated as 1 and odds as 0, so someArray would end up with 0 in its odd indices and 1 in its even indices.

This is an example to illustrate what I’d like to do.

Is there a way to do this in Python without the usage of control flow, simply within the mathematical expression itself? not evaluates a boolean, and not a 1 or a 0.

I ask because I am setting the attribute of something +-1 based on whether a certain count is even or odd, and it is nested inside multiple other specifiers.

Asked By: user20896951

||

Answers:

You can achieve this using list comprehension in python.

n = 10
some_array = [1 if not i%2 else -1 for i in range(n)]

In python not operator is used to negate the truthiness of value, not to negate numeric value.

Answered By: Kiran Kandel

You could explicitly cast the bool to int after adding not to the remainder calculation like so:

n = 10 #example length

#list initialization 
some_list = [0]*n

for i in range(n):
    some_list[i] = int(not i%2)

You can also make the list a boolean list and use map as well.

Here’s a link to more details on this topic

Answered By: Ping34
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.