The table below presents a quick overview of all Python operators.
Some basic examples for some operators very specific to Python are found below this overview.
OPERATOR | LOOKS LIKE | FUNCTION | EXAMPLES |
---|---|---|---|
Is | = | Assigns value to object | myString = 'Ruben' |
Equal to | == | Compares if values are equal | if myString == 'Chrissy': |
Not equal to | != | Compares if values are not equal | if myString != 'Ruben': |
Less than | < | Compares if value is less than | if myAge < 30: |
Less than or equal to | <= | Compares if value is less than or equal to | if myAge <= 30: |
Greater than | > | Compares if value is greater than | if myAge > 30: |
Greater than or equal to | >= | Compares if value is greater than or equal to | if myAge >= 30: |
Identity equal | is | Checks if objects have equal IDs | if myAge is None: |
Identity not equal | is not | Checks if objects have different IDs | if myAge is not None: |
In | in | Checks if object contains other object | if 'a' in 'banana': |
And | and | Checks if 2 conditions are both True | if 'a' in 'banana' and 'c' in 'cherry': |
Or | or | Checks if at least 1 of multiple conditions is True | if 'a' in 'banana' or 'b' in 'cherry': |
Not | not | Checks if condition is False | if not 'c' in 'banana': |
Backslash | \ | Escape (special or normal) character | print('new line starts\nhere') |
Hash | # | Indicates that rest of line if comment | #LOOP OVER VARIABLES STARTS HERE |
Square brackets | [] | Extracts part of object such as substring Indicates Python list object | myString = 'Ruben'[0] |
Parentheses | () | Combines conditions Indicates Python tuple | if ('a' in 'banana' or 'b' in 'banana') and 'd' in 'cherry': |
Curly brackets | {} | Placeholder for Python text replacement Indicates Python dict object | 'Just say {}!'.format('hello') |
Plus | + | Add 2 or more numbers Add element to object such as concatenation | fullName = 'Ruben' + ' van den Berg' |
Minus | - | Subtraction for numbers | 10 - 9 |
Asterisk | * | Multiplication for numbers | 10 * 9 |
Slash | / | Division for numbers | 10 / 2 |
Double asterisk | ** | Power for numbers | 2 ** 10 |
Double slash | // | Floor division for numbers | 3 // 2 |
Percent | % | Modulus for numbers Text replacement in strings | 3 % 2 |
Plus-is | += | Add number to existing number Add element to object such as concatenation | cntr += 1 |
Python “Less Than” Operator
A minor note regarding the Python <, <=, > and >= operators is that they also apply to strings. In this case, they roughly refer to the alphabetical order of those strings.
print('a' < 'b') # True
print('a' > 'b') # False
end program.
More precisely, the aforementioned operators compare if Unicode code points underlying characters are smaller/larger. This is why capital letters are always smaller than their lower case counterparts.
print('a' < 'A') ## False
print('a' > 'A') ## True
end program.
Most (but not all) special characters precede all numbers, which precede all letters.
print('#' < '5') # True
print('5' < 'Z') # True
end program.
Python “Is” Operator
In Python, “is” evaluates if 2 objects share the same ID. When comparing Python objects, we usually compare if their values are equal. A stricter comparison, however, is whether their IDs are equal too. The syntax below shows a quick example.
begin program python3.
myName = 'Ruben'
yourName = 'Rube'
yourName += 'n'
print(myName,yourName) # Ruben Ruben
print(myName == yourName) # True
print(id(myName),id(yourName)) # 51019032 51016008
print(myName is yourName) # False
end program.
If 2 objects have the same ID, then they are basically just different names for the same object. In this case, a change to one of them applies to the other as well.
begin program python3.
myList = [1,3,5]
yourList = myList
print(myList is yourList) # True
myList.append(7) # Applies to 'both' lists
print(myList,yourList) # [1, 3, 5, 7] [1, 3, 5, 7]
end program.
*CREATE 2 LIST OBJECTS WITH DIFFERENT IDS.
begin program python3.
myList = [1,3,5]
yourList = myList[:]
print(myList is yourList) # False
myList.append(7) # Applies only to myList
print(myList,yourList) # [1, 3, 5, 7] [1, 3, 5]
end program.
Python “In” Operator
The Python “in” operator evaluates if some object contains another object. Basic examples are
- does some Python string contain some substring?
- does some Python list contain some string?
- does some Python tuple contain some integer?
begin program python3.
myFruit = 'banana'
print('an' in myFruit) # True
end program.
*CHECK IF LIST CONTAINS SUBTRING.
begin program python3.
myFruit = ['apple','banana','cherry']
print('apple' in myFruit) # True
end program.
Note that the “in” operator is a bit tricky for Python dict objects: it only inspects if some object is among the dict keys, not its values.
begin program python3.
myFruit = {'a':'apple','b':'banana','c':'cherry'}
print('a' in myFruit) # True
print('apple' in myFruit) # False
end program.
*USE "VALUES" METHOD FOR SEARCHING DICT VALUES.
begin program python3.
print('apple' in myFruit.values()) # True
end program.
Backslashes in Python
In Python, a backslash indicates an escape sequence: a combination of 2 characters where the first modifies the meaning of the second. This works in 2 directions:
- a backslash gives a special meaning to “normal” characters and
- a backslash abolishes the special meaning of special characters.
A common example of the first type is \n, in which the backslash changes the meaning of the n from simply “n” to a line break.
print('New line starts\nhere')
end program.
An example of the second type is \', in which the backslash changes the special meaning of ' (start of a string) to simply “'”.
print('I don\'t know!') # I don't know!
end program.
For specifying paths in Python (especially when using the os module), we often need to escape the backslash itself. We do so by either using 2 backslashes or by specifying a path as a raw string by preceding it with “r”.
begin program python3.
myPath = 'D:\\SCRIPTS\\NEW FOLDER'
print(myPath) # D:\SCRIPTS\NEW FOLDER
end program.
*ESCAPE BACKSLASHES BY RAW STRING.
begin program python3.
yourPath = r'D:\SCRIPTS\NEW FOLDER'
print(yourPath) # D:\SCRIPTS\NEW FOLDER
end program.
Square Brackets in Python
In Python, square brackets either
- extract a part from some object such as a substring or
- indicate a Python list object.
The syntax below gives a handful of examples for extracting elements from objects, a procedure known as “slicing” in Python.
begin program python3.
myName = 'Ruben Geert van den Berg'
print(myName[:5]) # Ruben
end program.
*EXTRACT LAST ELEMENT FROM TUPLE.
begin program python3.
myTuple = (1,3,5,7,9)
print(myTuple[-1]) # 9
end program.
*EXTRACT DICT VALUE FOR KEY = 'a'.
begin program python3.
myFruit = {'a':'apple','b':'banana','c':'cherry'}
print(myFruit['a']) # apple
end program.
Square brackets around zero or more objects tell you that these make up a Python list object.
begin program python3.
animals = []
print(type(animals)) # <class 'list'>
end program.
begin program python3.
print(animals) # [] tells you that animals is a list object
end program.
Parentheses in Python
In Python, parentheses either
- group 2 or more conditions or
- indicate a Python tuple.
As the examples below suggest, it may be a good idea to always use parentheses for combining 3 or more conditions using “and” and “or” operators.
begin program python3.
if ('a' in 'banana' or 'b' in 'banana') and 'd' in 'cherry':
print('Yes!')
else:
print('No!')
end program.
*FIRST CONDITION MUST BE TRUE.
begin program python3.
if 'a' in 'banana' or ('b' in 'banana' and 'd' in 'cherry'):
print('Yes!')
else:
print('No!')
end program.
*UNCLEAR HOW CONDITIONS COMBINE...
begin program python3.
if 'a' in 'banana' or 'b' in 'banana' and 'd' in 'cherry':
print('Yes!')
else:
print('No!')
end program.
Curly Brackets in Python
In Python, curly brackets either
- make up a placeholder for a text replacement or
- indicate a Python dict object.
We'll cover different options for text replacements in SPSS Python Text Replacement Tutorial but we'll also add a minimal example below.
begin program python3.
myGreeting = 'hello'
print('Just say {}!'.format(myGreeting))
end program.
The examples below demonstrate that curly brackets also indicate a Python dict object.
begin program python3.
myFruit = {'a':'apple','b':'banana','c':'cherry'}
print(myFruit) # {'c': 'cherry', 'b': 'banana', 'a': 'apple'}
print(type(myFruit)) # <class 'dict'>
end program.
Python Plus Operator
In Python, the plus operator either
- adds 2 or more numbers (such as int or float objects) or
- adds 1 or more elements to an object.
The example below demonstrates numeric addition.
begin program python3.
myInt = 5
myFloat = 1.23
print(myInt + myFloat) # 6.23
end program.
For objects other than numbers -such as strings or lists- the plus operator adds elements to them. Like so, the examples below demonstrate a concatenation for a string object and adding a list to another list.
begin program python3.
myDay = '23'
myMonth = 'February'
myYear = '2022'
myDate = myDay + ' ' + myMonth + ' ' + myYear
print(myDate) # 23 February 2022
end program.
*ADD LIST TO LIST WITH +. NOTE: USE += FOR CHANGING MYLIST.
begin program python3.
myList = [1,3,5]
print(myList + [7,9,11])
end program.
*ADD LIST TO LIST WITH EXTEND.
begin program python3.
myList = [1,3,5]
myList.extend([7,9,11])
print(myList)
end program.
Double Asterisk in Python
A double asterisk in Python raises some number to some power.
begin program python3.
for pow in range(10):
print(2 ** pow)
end program.
Quick note: you can use something like myNumber**(1 / k) for finding the k-th root for some number, including the square root. In contrast to Excel, Googlesheet and SPSS, sqrt() is not available in Python unless you import the math module and use math.sqrt().
Double Slash in Python
A double slash in Python is used for floor division: it divides x by y and truncates the result.
begin program python3.
print(10 // 3) # 3
end program.
Percent Signs in Python
In Python, a percent sign is either used
- for the modulo function for numbers or
- as a placeholder for a text replacement in string objects.
First off, the modulo (not to be confused with modulus) returns the remainder after subtracting x from y as many times as possible. Like so, it can be used to check if numbers are odd or even.
begin program python3.
for myInt in range(10):
if (myInt % 2): # SHORTHAND FOR MODULO NOT ZERO
print('%s is an odd number.'%myInt)
else:
print('%s is an even number.'%myInt)
end program.
Second, percent signs are used as placeholders for text replacements in Python. Precisely,
- %s can be replaced by a string value,
- %d can be replaced by an integer number and
- %f can be replaced by a floating point number.
Note that these placeholders are somewhat deprecated over curly brackets with .format(). The syntax below shows minimal examples for both methods.
begin program python3.
name = 'Alexander'
age = 43
print('%s is %d years old.'%(name,age)) # Alexander is 43 years old.
end program.
*TEXT REPLACEMENTS WITH {} PLACEHOLDERS.
begin program python3.
name = 'Alexander'
age = 43
print('{} is {} years old.'.format(name,age)) # Alexander is 43 years old.
end program.
Python Plus-Is Operator
In Python, the plus-is operator is used for
- adding a number to another number or
- adding an element to some other object.
In either case, a += b is nothing more than a shorthand for a = a + b. The syntax below gives a quick example for numeric objects.
begin program python3.
myInt = 5
myInt = myInt + 3
print(myInt) # 8
end program.
*ADD 3 TO MYINTO VIA PLUS-IS OPERATOR.
begin program python3.
myInt = 5
myInt += 3
print(myInt) # 8
end program.
Apart from numeric addition, the += operator can also be used for concatenating strings or adding elements to Python list objects. In the latter case, it acts as .extend rather than .append as shown below.
begin program python3.
myVars = ''
for ind in range(10):
myVars += 'v%s '%ind
print(myVars) # ['v0', 'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9']
end program.
*FOR LIST, += OPERATOR IS SIMILAR TO EXTEND (NOT APPEND).
begin program python3.
myVars = []
for ind in range(10):
myVars += ['v' + str(ind)]
print(myVars) # v0 v1 v2 v3 v4 v5 v6 v7 v8 v9
end program.
Right, so I guess that should do regarding Python operators. If you've any questions or remarks, please let us know.
Thanks for reading!