0% found this document useful (0 votes)
36 views12 pages

Common Sequence Operations

Common sequence operations include indexing, slicing, length, membership testing, concatenation, repetition, minimum/maximum and methods like index, count. Mutable sequence types allow item assignment, deletion, slice assignment and methods like append, insert, pop. String methods include islower, isnumeric, isupper, join, lower, lstrip, rstrip, strip, replace and more. Set operations include union, intersection, difference, symmetric difference, subset/superset testing and methods like add, remove, discard. Dictionary methods include constructor forms, getting/setting items, length, deletion, iteration, clear and copy.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views12 pages

Common Sequence Operations

Common sequence operations include indexing, slicing, length, membership testing, concatenation, repetition, minimum/maximum and methods like index, count. Mutable sequence types allow item assignment, deletion, slice assignment and methods like append, insert, pop. String methods include islower, isnumeric, isupper, join, lower, lstrip, rstrip, strip, replace and more. Set operations include union, intersection, difference, symmetric difference, subset/superset testing and methods like add, remove, discard. Dictionary methods include constructor forms, getting/setting items, length, deletion, iteration, clear and copy.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Common Sequence Operations

Operation Result

x in s True if an item of s is equal to x, else False


x not in s False if an item of s is equal to x, else True
s+t the concatenation of s and t
s * n or n * s equivalent to adding s to itself n times
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
index of the first occurrence of x in s (at or after
s.index(x[, i[, j]])
index i and before index j)
s.count(x) total number of occurrences of x in s
Mutable Sequence Types
Operation Result
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
appends x to the end of the sequence (same
s.append(x)
as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += extends s with the contents of t (for the most part the same
t as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop([i]) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] == x
s.reverse() reverses the items of s in place
String Methods
• str.islower()Return true if all cased characters [4] in the string are lowercase and there is at least one cased
character, false otherwise.
• str.isnumeric()Return true if all characters in the string are numeric characters, and there is at least one
character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode
numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with
the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
• str.isupper()Return true if all cased characters [4] in the string are uppercase and there is at least one cased
character, false otherwise.
• str.join(iterable)Return a string which is the concatenation of the strings in the iterable 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.
• str.lower()Return a copy of the string with all the cased characters [4] converted to lowercase.
• str.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 None, the chars argument defaults to removing
whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:
• str.replace(old, new[, count])¶Return a copy of the string with all occurrences of substring old replaced by new. If
the optional argument count is given, only the first count occurrences are replaced.
• str.rsplit(sep=None, maxsplit=-1)Return 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 None, any
whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described
in detail below.
• str.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 None, the chars argument defaults to removing
whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:
• str.strip([chars])Return a copy of the string with the leading and trailing characters removed. The chars argument
is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to
removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are
stripped:
• str.swapcase()Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note
that it is not necessarily true that s.swapcase().swapcase() == s.
• str.count(sub[, start[, end]])
Return 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.
• str.endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple
of suffixes to look for. With optional start, test beginning at that position. With optional end, stop
comparing at that position.
• str.find(sub[, start[, end]])
Return 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. Return -1 if sub is not found.
• str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.
• str.isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false
otherwise. Alphabetic characters are those characters defined in the Unicode character database as
“Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that
this is different from the “Alphabetic” property defined in the Unicode Standard.
• str.isdecimal()
Return true if all characters in the string are decimal characters and there is at least one character, false
otherwise. Decimal characters are those from general category “Nd”. This category includes digit
characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-
INDIC DIGIT ZERO.
• str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
Digits include decimal characters and digits that need special handling, such as the compatibility
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 differen
len(s)
Return the cardinality of set s.
x in s
Test x for membership in s.
x not in s
Test x for non-membership in s.
isdisjoint(other)
Return True if the set has no elements in common with other. Sets are disjoint if and only if
their intersection is the empty set.
issubset(other)
set <= other-Test whether every element in the set is in other.
set < other
Test whether the set is a proper subset of other, that is, set <= other and set != other.
issuperset(other)
set >= other Test whether every element in other is in the set.
set > other
Test whether the set is a proper superset of other, that is, set >= other and set != other.
union(other, ...)
set | other | ...Return a new set with elements from the set and all others.
intersection(other, ...)
set & other & ...Return a new set with elements common to the set and all others.
difference(other, ...)
set - other - ... Return a new set with elements in the set that are not in the others.
symmetric_difference(other)
set ^ other Return a new set with elements in either the set or other but not both.
copy()
Return a new set with a shallow copy of s.
• add(elem)Add element elem to the set.
• remove(elem)Remove element elem from the
set. Raises KeyError if elem is not contained in the
set.
• discard(elem)Remove element elem from the set
if it is present.
• pop()Remove and return an arbitrary element
from the set. Raises KeyError if the set is empty.
• clear()¶Remove all elements from the set.
Dictionary
a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
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.
del d[key]
Remove d[key] from d. Raises a KeyError if key is not in the map.
key in d
Return True if d has a key key, else False.
key not in d
Equivalent to not key in d.
iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for
iter(d.keys()).
clear()
Remove all items from the dictionary.
copy()
Return a shallow copy of the dictionary.
classmethod fromkeys(seq[, value])
Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.
get(key[, default])
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.
items()
Return a new view of the dictionary’s items ((key, value) pairs). See the
documentation of view objects.
keys()
Return a new view of the dictionary’s keys. See the documentation of view
objects.
pop(key[, default])
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.
popitem()
Remove and return an arbitrary (key, value) pair from the dictionary.
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.
setdefault(key[, default])
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.

update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys.
Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as
tuples or other iterables of length two). If keyword arguments are specified, the
dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

values()
Return a new view of the dictionary’s values. See the documentation of view objects.

You might also like