Methods and Functions Python
Methods and Functions Python
append(x) Adds an item (x) to the end of the list. This is equivalent to a[len(a):] = [x].
extend(iterable) Extends the list by appending all the items from the iterable. This allows you to join two lists together.
This method is equivalent to a[len(a):] = iterable.
insert(i, x) Inserts an item at a given position. The first argument is the index of the element before which to insert.
For example, a.insert(0, x) inserts at the front of the list.
remove(x) Removes the first item from the list that has a value of x. Returns an error if there is no such item.
pop([i]) Removes the item at the given position in the list, and returns it. If no index is specified, pop() removes
and returns the last item in the list.
index(x[, start[, end]] Returns the position of the first list item that has a value of x. Raises a ValueError if there is no such
) item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the
search to a particular subsequence of the list. The returned index is computed relative to the beginning
of the full sequence rather than the start argument.
sort(key=None, Sorts the items of the list in place. The arguments can be used to customize the operation.
reverse=False)
key
Specifies a function of one argument that is used to extract a comparison key from each list
element. The default value is None (compares the elements directly).
reverse
Boolean value. If set to True, then the list elements are sorted as if each comparison were
reversed.
Use the copy() method when you need to update the copy without affecting the original list.
If you don't use this method (eg, if you do something like list2 = list1), then any updates
you do to list2 will also affect list1.
Method Description
len(s) Returns the number of items in the list.
The len() function can be used on any sequence (such as a string, bytes, tuple, list, or range) or
collection (such as a dictionary, set, or frozen set).
max(iterable, Returns the largest item in an iterable (eg, list) or the largest of two or more arguments.
*[, key, default])
The default argument specifies an object to return if the provided iterable is empty. If the iterable is
max(arg1, arg2,
*args[, key]) empty and default is not provided, a ValueError is raised.
If more than one item shares the maximum value, only the first one encountered is returned.
min(iterable, Returns the smallest item in an iterable (eg, list) or the smallest of two or more arguments.
*[, key, default])
The default argument specifies an object to return if the provided iterable is empty. If the iterable is
min(arg1, arg2,
*args[, key]) empty and default is not provided, a ValueError is raised.
If more than one item shares the minimum value, only the first one encountered is returned.
range(stop) Represents an immutable sequence of numbers and is commonly used for looping a specific number
of times in for loops.
or
It can be used along with list() to return a list of items between a given range.
range(start, stop[, step]
)
Strictly speaking, range() is actually a mutable sequence type.
Method Description
capitalize() Returns a copy of the string with its first character capitalized and the rest lowercased.
Use title() if you want the first character of all words capitalized (i.e. title case).
casefold() Returns a casefolded copy of the string. Casefolded strings may be used for caseless
matching.
center(width[, fillchar]) Returns the string centered in a string of length width. Padding can be done using the
specified fillchar (the default padding uses an ASCII space). The original string is returned
if width is less than or equal to len(s)
count(sub[, start[, end]]) Returns the number of non-overlapping occurrences of substring (sub) in the range
[start, end]. Optional arguments start and end are interpreted as in slice notation.
encode(encoding="utf-8", Returns an encoded version of the string as a bytes object. The default encoding is utf-
errors="strict") 8. errors may be given to set a different error handling scheme. The possible value
for errors are:
expandtabs(tabsize=8) Returns a copy of the string where all tab characters are replaced by one or more spaces,
depending on the current column and the given tab size. Tab positions occur every tabsize
characters (the default is 8, giving tab positions at columns 0, 8, 16 and so on).
find(sub[, start[, end]]) Returns the lowest index in the string where substring sub is found within the
slice s[start:end]. Optional arguments start and end are interpreted as in slice notation.
Returns -1 if sub is not found.
The find() method should only be used if you need to know the position of the substring. If
you don't need to know its position (i.e. you only need to know if the substring exists in the
string), use the in operator. See string operators for an example of in.
format(*args, **kwargs) Performs a string formatting operation. The string on which this method is called can
contain literal text or replacement fields delimited by braces {}. Each replacement field
contains either the numeric index of a positional argument, or the name of a keyword
argument. Returns a copy of the string where each replacement field is replaced with the
string value of the corresponding argument.
format_map(mapping) Similar to format(**mapping), except that mapping is used directly and not copied to a
dictionary. This is useful if for example mapping is a dict subclass.
index(sub[, start[, end]]) Like find() (above), but raises a ValueError when the substring is not found
(find() returns -1 when the substring isn't found).
isalnum() Returns True if all characters in the string are alphanumeric and there is at least one
character. Returns False otherwise.
c.isalpha()
c.isdecimal()
c.isdigit()
c.isnumeric()
isalpha() Returns True if all characters in the string are alphabetic and there is at least one character.
Returns False otherwise.
Note that "alphabetic" in this case are those characters defined in the Unicode character
database as "Letter". These are the characters with the general category property being one
of "Lm", "Lt", "Lu", "Ll", or "Lo". This is different from the "Alphabetic" property defined
in the Unicode Standard.
isdecimal() Returns True if all characters in the string are decimal characters and there is at least one
character. Returns False otherwise.
Decimal characters are those that can be used to form numbers in base 10. Decimal
characters are those in the Unicode General Category "Nd".
You can see the difference between isdigit() and isdecimal() by the way they handle the
second example (u"\u00B2").
isdigit() Returns True if all characters in the string are digits and there is at least one character.
Returns False otherwise.
The isdigit() method is often used when working with various unicode characters, such as
for superscripts (eg, 2).
You can see the difference between isdigit() and isdecimal() by the way they handle the
second example (u"\u00B2").
isidentifier() Returns true if the string is a valid identifier according to the language definition,
section Identifiers and keywords from the Python docs.
islower() Returns True if all cased characters in the string are lowercase and there is at least one cased
character. Returns False otherwise.
Cased characters are those with general category property being one of "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
You can use casefold() to force a string to lowercase (as demonstrated by the last
example).
isnumeric() Returns True if all characters in the string are numeric characters, and there is at least one
character. Returns False otherwise.
Numeric characters include digit characters, and all characters that have the Unicode
numeric value property. Numeric characters are those with the property
value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
isprintable() Returns True if all characters in the string are printable or the string is empty.
Returns False otherwise.
Nonprintable characters are those characters defined in the Unicode character database as
"Other" or "Separator", except for the ASCII space (0x20) which is considered printable.
Printable characters in this context are those which should not be escaped when repr() is
invoked on a string. It has no bearing on the handling of strings written
to sys.stdout or sys.stderr.
isspace() Returns True if there are only whitespace characters in the string and there is at least one
character. Returns False otherwise.
Whitespace characters are those characters defined in the Unicode character database as
"Other" or "Separator" and those with bidirectional property being one of "WS", "B", or
"S".
istitle() Returns True if the string is a titlecased string and there is at least one character (for
example uppercase characters may only follow uncased characters and lowercase characters
only cased ones). Returns False otherwise.
Whitespace characters are those characters defined in the Unicode character database as
"Other" or "Separator" and those with bidirectional property being one of "WS", "B", or
"S".
isupper() Returns True if all cased characters in the string are uppercase and there is at least one cased
character. Returns False otherwise.
Cased characters are those with general category property being one of "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
join(iterable) Returns a string which is the concatenation of the strings in iterable. A TypeError will be
raised if there are any non-string values in iterable, including bytes objects. The separator
between elements is the string providing this method.
ljust(width[, fillchar]) Returns the string left justified in a string of length width. Padding can be done using the
specified fillchar (the default padding uses an ASCII space). The original string is returned
if width is less than or equal to len(s)
lower() Returns a copy of the string with all the cased characters converted to lowercase.
lstrip([chars]) Return a copy of the string with leading characters removed. The chars argument is a string
specifying the set of characters to be removed. If omitted or set to None, the chars argument
defaults to removing whitespace.
Note that the chars argument is not a prefix — all combinations of its values are stripped.
maketrans(x[, y[, z]]) This is a static method that returns a translation table usable for str.translate().
partition(sep) Splits the string at the first occurrence of sep, and returns a 3-tuple containing the part
before the separator, the separator itself, and the part after the separator. If the separator is
not found, it returns a 3-tuple containing the string itself, followed by two empty strings.
replace(old, new[, count]) Returns a copy of the string with all occurrences of substring old replaced by new. If the
optional argument count is provided, only the first count occurrences are replaced. For
example, if count is 3, only the first 3 occurrences are replaced.
rfind(sub[, start[, end]]) Returns the highest index in the string where substring sub is found, such that sub is
contained within s[start:end]. Optional arguments start and end are interpreted as in slice
notation. This method returns -1 on failure.
rjust(width[, fillchar]) Returns the string right justified in a string of length width. Padding can be done using the
specified fillchar (the default padding uses an ASCII space). The original string is returned
if width is less than or equal to len(s)
rpartition(sep) Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before
the separator, the separator itself, and the part after the separator. If the separator is not
found, it returns a 3-tuple containing the string itself, followed by two empty strings.
rsplit(sep=None, maxsplit=-1) Returns a list of the words in the string, using sep as the delimiter string. If maxsplit is
given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or is set
to None, any whitespace string is a separator.
Except for splitting from the right, rsplit() behaves like split() which is described below.
rstrip([chars]) Return a copy of the string with trailing characters removed. The chars argument is a string
specifying the set of characters to be removed. If omitted or set to None, the chars argument
defaults to removing whitespace.
Note that the chars argument is not a suffix — all combinations of its values are stripped.
split(sep=None, maxsplit=-1) Returns a list of the words in the string, using sep as the delimiter string. If maxsplit is
given, at most maxsplit splits are done. If maxsplit is not specified or -1, then there is no
limit on the number of splits.
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit
empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']).
If sep is not specified or is set to None, a different splitting algorithm is applied: runs of
consecutive whitespace are regarded as a single separator, and the result will contain no
empty strings at the start or end if the string has leading or trailing whitespace.
Consequently, splitting an empty string or a string consisting of just whitespace with
a None separator returns [].
splitlines([keepends]) Returns a list of the lines in the string, breaking at line boundaries. Line breaks are not
included in the resulting list unless keepends is given and its value is True.
Representatio Description
n
\n Line Feed
\r Carriage Return
\u2029 Paragraph
separator
startswith(prefix[, start[, end]] Returns True if the string starts with the specified prefix, otherwise it
) returns False. prefix can also be a tuple of prefixes. When the (optional) start argument is
provided, the test begins at that position. With optional end, the test stops comparing at that
position.
strip([chars]) Returns a copy of the string with leading and trailing characters removed.
The chars argument is a string specifying the set of characters to be removed. If omitted or
set to None, the chars argument defaults to removing whitespace.
Note that the chars argument is not a prefix or suffix — all combinations of its values are
stripped.
swapcase() Returns a copy of the string with uppercase characters converted to lowercase and vice
versa.
Note that using swapcase() twice on a string will not always return it to its original case.
There are some cases where two different lowercase characters share an uppercase
character, and therefore, swapping case could have an unintended effect. See this Q/A on
Stack Overflow for examples.
title() Returns a title-cased version of the string. Title case is where words start with an uppercase
character and the remaining characters are lowercase.
translate(table) Returns a copy of the string in which each character has been mapped through the given
translation table. The table must be an object that implements indexing via __getitem__(),
typically a mapping or sequence.
upper() Returns a copy of the string with all the cased characters converted to uppercase.
zfill(width) Returns a copy of the string left filled with ASCII 0 digits to make a string of length width.
A leading sign prefix (+/-) is handled by inserting the padding after the sign character rather
than before. The original string is returned if width is less than or equal to len(s).
NUMBER OPERATORS
Operation Result
x + y Sum of x and y
x - y Difference of x and y
x * y Product of x and y
x / y Quotient of x and y
x // y Floored quotient of x and y
x % y Remainder of x / y
-x x negated
+x x unchanged
abs(x) Absolute value or magnitude of x
int(x) x converted to integer
float(x) x converted to float
complex(re, A complex number with real part re, imaginary part im. im defaults to zero.
im)
Operation Result
math.trunc(x x truncated to Integral
)
round(x[, x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
n])
Operation Result
x | y Bitwise or of x and y
x ^ y Bitwise exclusive of x and y
x & y Bitwise exclusive of x and y
x << n x shifted left by n bits
x >> n x shifted right by n bits
~x The bits