Adapted from https://docs.python.org/3/library/stdtypes.html.
bool
Boolean values are the two constant objects False
and True
. They are used to represent truth values.
int
, float
There are two distinct numeric types: integers and floating point numbers. Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals yield integers. Numeric literals containing a decimal point or an exponent sign yield floating point numbers.
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point. Comparisons between numbers of mixed type use the same rule.
All numeric types support the following operations (for priorities of the operations, see Operator precedence):
Operation | Description |
---|---|
x + y |
Returns the sum of
|
x - y |
Returns the difference of
|
x * y |
Returns the product of
|
x / y |
Returns the quotient of
|
x // y |
Returns the floored quotient of
|
x % y |
Returns the remainder of
|
x ** y |
Returns
|
-x |
Returns
|
int(x) |
Returns
|
float(x) |
Returns
|
math.floor(x) |
Returns the greatest integer
|
math.ceil(x) |
Returns the least integer
|
See also the built-in functions abs
, divmod
, pow
, and round
.
str
, list
, tuple
The operations in the following table are supported by most sequence types, both mutable and immutable.
Operation | Description |
---|---|
x in s |
Returns
|
x not in s |
Returns
|
s + t |
Returns the concatenation of
|
s * n or n * s |
Returns the equivalent to adding
|
s[i] |
Returns the
|
s[i:j] |
Returns the slice of
|
s[i:j:k] |
Returns the slice of
|
s.index(x[, i[, j]]) |
Returns the
|
s.count(x) |
Returns the total number of occurrences of
|
See also the built-in functions len
, max
, and min
.
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.
list
The list
data type supports all of the immutable sequence operations from the previous section, as well as the following operations.
Operation | Description |
---|---|
s[i] = x |
Set the item at index
|
list.append(self, x) |
Appends
|
list.extend(self, t) or self += t |
Extends
|
list.insert(self, i, x) |
Inserts
|
list.pop(self[, i]) |
Returns the item at
|
list.remove(self, x) |
Removes the first occurrence of
|
list.reverse(self) |
Reverses the items of self in place (mutates self ). |
|
Sorts
The Example:
|
str
Textual data in Python is handled with str
objects, or strings. Strings are immutable sequences.
Triple quoted strings may span multiple lines—all associated whitespace will be included in the string literal.
Strings may also be created from other objects using the str
constructor.
Since there is no separate “character” type, indexing a string produces strings of length 1. That is, for a non-empty string s
, s[0] == s[0:1]
. Strings implement all of the common sequence operations, along with the additional methods described below.
Operation | Description |
---|---|
str.capitalize(self) |
Return a copy of the string with its first character capitalized and the rest lowercased. Example:
|
|
Return the number of non-overlapping occurrences of substring Optional arguments Example:
|
|
Return With optional Example:
|
str.find(self, sub[, start[, end]]) |
Return the lowest index in the string where substring Optional arguments Example:
Return -1 if Note: The
|
|
Like Example:
|
str.isalnum(self) |
Return Example:
|
str.isalpha(self) |
Return Example:
|
str.isdigit(self) |
Return
|
str.islower(self) |
Return Example:
|
str.isnumeric(self) |
Return Example:
|
str.isupper(self) |
Return Example:
|
str.join(self, iterable) |
Return a string which is the concatenation of the strings in Example:
|
str.lower(self) |
Return a copy of the string with all the cased characters converted to lowercase. Example:
|
|
Return a copy of the string with all occurrences of substring Example:
|
|
Return a list of the words in the string, using If Splitting an empty string with a specified separator returns [’’]. Example:
If |
|
Return True if string starts with the prefix , otherwise return False . With optional start , test string begins at that position. With optional end , stop comparing string at that position. |
str.strip(self, [chars]) |
Return a copy of the string with the leading and trailing characters removed. The The Example:
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. Example:
|
set
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
Like other collections, sets support x in set, len(set)
, and for x in set
. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
The set type is mutable—the contents can be changed using methods like add()
and remove()
. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set.
Non-empty sets can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}
, in addition to the set
constructor.
Operation | Description |
---|---|
len(self) |
Return the size (number of elements) of self . |
x in self |
Return whether x is in self . |
x not in self |
Return whether x is not in self . |
set.isdisjoint(self, other) |
Return whether the set self has no elements in common with other . Sets are disjoint if and only if their intersection is the empty set. |
set.issubset(self, other) |
Return whether every element in the set self is in other . Can also use self <= other . |
self < other |
Return whether the set self is a proper subset of other , that is, self <= other and self != other . |
set.issuperset(self, other) |
Return whether every element in other is in the set self . Can also use self >= other . |
self > other |
Return whether the set self is a proper superset of other , that is, self >= other and self != other . |
set.union(self, *others) |
Return a new set with elements from the set and all others. |
set.intersection(self, *others) |
Return a new set with elements common to the set and all others. |
set.difference(self, *others) |
Return a new set with elements in the set that are not in the others. |
set.symmetric_difference(self, other) |
Return a new set with elements in either the set or other but not both. |
set.update(self, *others) |
Update the set, adding elements from all others. |
set.intersection_update(self, *others) |
Update the set, keeping only elements found in it and all others. |
set.difference_update(self, *others) |
Update the set, removing elements found in others. |
set.symmetric_difference_update(self, other) |
Update the set, keeping only elements found in either set, but not in both. |
set.add(self, elem) |
Add element elem to the set . |
set.remove(self, elem) |
Remove element elem from the set. Raises KeyError if elem is not contained in the set. |
set.discard(self, elem) |
Remove element elem from the set if it is present. |
set.pop(self) |
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty. |
set
supports set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).
dict
A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.
Dictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127}
or {4098: 'jack', 4127: 'sjoerd'}
, or by the dic
t constructor.
These are the operations that dictionaries support (and therefore, custom mapping types should support too):
Operation | Description |
---|---|
list(d) |
Return a list of all the keys used in the dictionary d . |
len(d) |
Return the number of items in the dictionary d . |
d[key] |
Return the item of d with key key . Raises a KeyError if key is not in the map. |
d[key] = value |
Set d[key] to value . |
key in d |
Return True if d has a key key , else False . |
key not in d |
Equivalent to not key in d . |
|
Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError . |
dict.items(self) |
Return a new view of the dictionary’s items ((key, value) pairs). |
|
If key is in the dictionary, remove it and return its value, else return default If default is not given and key is not in the dictionary, a KeyError is raised. |
dict.popitem(self) |
Remove and return a (key, value) pair from the dictionary. Pairs are returned in last-in-first-out (LIFO) order. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError . |
|
If key is in the dictionary, return its value. If not, insert key with a value of default and return default . default defaults to None . |
Dictionaries compare equal if and only if they have the same (key, value) pairs (regardless of ordering). Order comparisons (<
, <=
, >=
>
) raise TypeError
.
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
'one': 1, 'two': 2, 'three': 3, 'four': 4}
{>>> list(d)
'one', 'two', 'three', 'four']
[>>> list(d.values())
1, 2, 3, 4]
[>>> d["one"] = 42
>>> d
'one': 42, 'two': 2, 'three': 3, 'four': 4}
{>>> del d["two"]
>>> d["two"] = None
>>> d
'one': 42, 'three': 3, 'four': 4, 'two': None} {
range
The range
type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
Constructor: range(stop)
or range(start, stop[, step])
.
The arguments to the range constructor must be integers. If the step
argument is omitted, it defaults to 1. If the start
argument is omitted, it defaults to 0. If step
is zero, ValueError
is raised.
For a positive step, the contents of a range r
are determined by the formula r[i] = start + step*i
where i >= 0
and r[i] < stop
.
For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i
, but the constraints are i >= 0
and r[i] > stop
.
Range examples:
>>> list(range(10))
0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[>>> list(range(1, 11))
1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[>>> list(range(0, 30, 5))
0, 5, 10, 15, 20, 25]
[>>> list(range(0, 10, 3))
0, 3, 6, 9]
[>>> list(range(0, -10, -1))
0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
[>>> list(range(0))
[]>>> list(range(1, 0))
[]
None
This object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None
(a built-in name).