Operators

Updated: 2018-06-26

Mod Operator

% operator

  • Python: returns the modulus and
  • Java: returns the remainder.

They give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results.

In Java, the positive value by:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;
  • (a + b) % p = (a % p + b % p) % p
  • (a - b) % p = (a % p - b % p) % p
  • (a * b) % p = (a % p * b % p) % p
  • a ^ b % p = ((a % p)^b) % p

Spread Operator

python vs es6: https://gist.github.com/revolunet/537a3448cff850231a74

Ternary

Python

There is no ternary operator(condition?a:b) in Python, but can use this

>>> "a" if 1 + 1 == 2 else "b"
'a'
>>> "a" if 1 + 1 > 2 else "b"
'b'

Elvis Operator

x = f() ?: g()

This is equivalent to

x = f() ? f() : g()

This is helpful to set a default value, so the returned value is always not null.

x = f() ?: "default value"

Null Coalescing Operator: ??

a ?? b

This is equivalent to

a != null ? a : b

Reading from left to right, the first value which exists and is not null is the value that will be returned.

a ?? b ?? c

The assignment operators and the ternary operator (?:) are right associative. All other binary operators are left associative.

Unpack

Python

The single star * unpacks the sequence/collection into positional arguments, so you can do this:

def sum(a, b):
    return a + b

values = (1, 2)

s = sum(*values)

This will unpack the tuple so that it actually executes as:

s = sum(1, 2)

The double star ** does the same, only using a dictionary and thus named arguments:

values = { 'a': 1, 'b': 2 }
s = sum(**values)

You can also combine:

def sum(a, b, c, d):
    return a + b + c + d

values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)

will execute as:

s = sum(1, 2, c=10, d=15)