CodeSkulptor3

Loading Documentation...

CodeSkulptor3 is a browser-based Python interpreter, as featured in the online course “Fundamentals of Computing”. It implements a subset of Python 3 plus the addition of three graphical libraries, SimpleGui, SimpleMap, and SimplePlot.

Types:

It does not support NotImplemented, Ellipsis, complex numbers, Unicode strings, bytearrays, frozensets, exceptions, xrange objects, or memory view objects.

Mutable types are those that have operations that mutate or update part of the value. Other types are immutable. Numbers, Booleans, strings, tuples, and functions are immutable, while all other types are mutable.

In Python, all values are objects, and objects can have attributes. Attributes that are functions are known as methods. An object is an instance of a class. Some classes are built-in, like lists and sets, but others can be user-defined.

For user-defined classes, Codeskulptor supports only “classic” or “old-style” classes, not “new-style” classes. It supports instance methods, but not the less commonly used class methods and static methods.

Hashable values are any for which the Python implementation defines a way to convert it into an integer (its hash value). In practice, a value is hashable if it is immutable. CodeSkulptor does not support the standard __hash__() method.

CodeSkulptor supports all forms of Python expressions.

Examples:

See the other sections of this documentation for details on which types, operations, functions, and methods are supported.

Simple Statements:
Examples:

Simple statements are those which cannot contain other statements. I.e., they are not compound. Note that in Python 3, print is no longer a statement and is now a function.

The only unsupported simple statements are exec, raise.

Compound Statements:
Examples:

Compound statements are those that can be built from smaller statements.

CodeSkulptor does not support try-except statements, with statements, “new-style” class definitions. (Note: try-except is partially implemented, but its use is not currently recommended.)

Good code and documentation style makes programs easier to read and debug. Using a style that is consistent with other programmers further helps others to read your code.

The Python Guide on Code Style provides a good summary with examples. For a more details, see the official Python style guides for code (“PEP 8”) and docstrings (“PEP 257”).

Operations:
Superclass:

The single value None is known as the null object. Its type is the NoneType. It serves as a placeholder return value for functions that would otherwise return nothing. It is also used as an special argument value to some operations, such as filter() and a_str.split().

Operations:
Superclass:
Tutorial:
Examples:
See also:
Math Module — Library of numeric operations

Integers have an arbitrary number of digits.

Floating-point numbers have a decimal point and a limited number of digits. Arithmetic operations on floating-point numbers can give somewhat inaccurate results because of the limited precision.

Examples:
CodeOutput
print(12)
12
print(-12.0)
-12
print(0b1001)
9
print(021)
17
print(-021)
-17
print(0x3A8)
936
print(12345678901234567890123456789012345678901234567890)
12345678901234567890123456789012345678901234567890
print(+12.12345)
12.12345
print(-12.12345)
-12.12345
print(1.2e3)
1200
print(1.2e-3)
0.0012

Integers can be given in any of four bases:

  • Base ten (decimal — what people are most used to): consists of a sequence of digits, not starting with 0
  • Base two (binary): consists of 0b followed by 0's and 1's
  • Base eight (octal): consists of a 0 followed by digits in the range 0 to 7
  • Base sixteen (hexadecimal): consists of 0x followed by digits in the range 0 to 7 or letters in the range A to F (in upper or lower case)

Integers can be preceded by a positive or negative sign.

Floating-point numbers consist of a series of digits, a decimal point, and another series of digits. They can be preceded by an optional positive or negative sign. They can be followed by an optional exponent — the letter e, an optional positive or negative sign, and a series of digits.

Syntax:
int(x)
float(x)

Examples:
CodeOutput
print(int())
0
print(int('234'))
234
print(int(1.6))
1
print(int(False))
0
print(float())
0.0
print(float('3.89'))
3.89
print(float('inf'))
inf
print(float('-inf'))
-inf
print(float(3))
3.0
print(float(False))
0.0
See also:
round() — Rounds to nearest integer
math.trunc() — Rounds to zero (same int() on integers)
math.ceil() — Rounds up
math.floor() — Rounds down

Given a number, int() returns the integer part of it, i.e., they round towards zero. Given a Boolean, they return zero (i.e., 0, or 0.0) for False, and one (i.e., 1, or 1.0) for True. Given a string containing a printed representation of an integer, int() returns that integer. Similarly, given a string containing a printed representation of a number, float() returns that number. Special cases for float() are the inputs "inf" and "-inf", representing positive and negative infinity, respectively. Given any other string, these raise a ValueError.

Syntax:
a + b

Examples:
CodeOutput
print(3 + 12)
15
print(3.0 + 12)
15.0
print(3 + 12.0)
15.0

Returns the sum of a and b. The result is an integer if both inputs are; otherwise, it is a floating-point. Standard addition operation.

Addition and assignment can be combined with the shorthand a += b, which is equivalent to a = a + b.

Syntax:
a - b
- a

Examples:
CodeOutput
print(12 - 3)
9
print(12.0 - 3)
9.0
print(12 - 3.0)
9.0
a = 3
print(-a)
-3

With two arguments, returns the difference of a and b. The result is an integer if both inputs are; otherwise, it is a floating-point. Standard subtraction operation.

With one argument, return the negation of a. Equivalent to 0 - a.

Subtraction and assignment can be combined with the shorthand a -= b, which is equivalent to a = a - b.

Syntax:
a * b

Examples:
CodeOutput
print(3 * 12)
36
print(3.0 * 12)
36.0
print(3 * 12.0)
36.0

Returns product of a and b. The result is an integer if both inputs are; otherwise, it is a floating-point. Standard multiplication operation.

Multiplication and assignment can be combined with the shorthand a *= b, which is equivalent to a = a * b.

Syntax:
a / b
a // b

Examples:
CodeOutput
print(12 / 3)
4.0
print(11 / 3)
3.6666666666666665
print(11 // 3)
3
print(12 / 3.0)
4.0
print(11.0 / 3)
3.6666666666666665
print(11.0 // 3.0)
3.0
Example:

The standard division operation, /, returns the quotient of a and b. The result is a floating-point number.

The integer division operation, //, returns the floor of the quotient of a and b, i.e., the integer part. The result is an integer if both inputs are; otherwise, it is a floating-point.

Division and assignment can be combined with the shorthand a /= b and a //= b, which are equivalent to a = a / b and a = a // b, respectively.

Syntax:
x % m

Example:
CodeOutput
print(11 % 3)
2

Returns the remainder of x // m.

Modulo and assignment can be combined with the shorthand x %= m, which is equivalent to x = x % m.

Syntax:
x ** y

Examples:
CodeOutput
print(3 ** 4)
81
print(3.0 ** 4)
81.0
print(3 ** 4.0)
81.0
See also:
pow() — Built-in exponentiation function
math.pow() and math.exp() — Similar exponentiation functions

Returns x to the power of y. The result is an integer if both inputs are; otherwise, it is a floating-point.

Exponentiation and assignment can be combined with the shorthand x **= y, which is equivalent to x = x ** y.

Syntax:
pow(x, y)
pow(x, y, m)

Examples:
CodeOutput
print(pow(3, 4))
81
print(pow(3.0, 4))
81.0
print(pow(3, 4.0))
81.0
print(pow(3, 4, 2))
1
See also:
** — Built-in exponentiation operator
math.pow() and math.exp() — Similar exponentiation functions

Given no m, this returns x to the power of y, just like x ** y. Given a integer m, this returns the remainder of integer x to the power of integer y, divided by m. The result is an integer if all inputs are; otherwise, it is a floating-point.

Syntax:
abs(x)

Examples:
CodeOutput
print(abs(3))
3
print(abs(-3.0))
3.0
See also:
math.fabs() — Always returns a floating-point number

Returns the absolute value of number x. The result is of the same type as the input.

Syntax:
round(n)
round(n, i)

Examples:
CodeOutput
print(round(12))
12
print(round(12.5))
13
print(round(-12.5))
-12
print(round(123.4567, 2))
123.46
print(round(123.4567, -2))
100.0
See also:
int() — Round to zero
math.trunc() — Rounds to zero
math.ceil() — Rounds up
math.floor() — Rounds down

With one number argument, it returns the integer nearest n.

With two number arguments, it returns the floating-point number that represents n rounded to the nearest unit of 10i, for integer i. I.e., when i is positive, this is the familiar idea of rounding to i places after the decimal. However, i can be zero or negative, as well.

In either case, a 5 digit is always rounded up.

Syntax:
bin(x)
oct(x)
hex(x)

Examples:
CodeOutput
print(bin(9))
0b1001
print(oct(-17))
-021
print(hex(936))
0x3a8

Given an integer, returns a string representing that number in binary, octal, or hexadecimal, respectively. The resulting string is in the same syntax as Python integer constants.

Syntax:
chr(i)

Example:
CodeOutput
print(chr(97))
a

Returns a string of one character whose ASCII code is the integer i. This is the inverse of ord().

Syntax:
ord(x)

Example:
CodeOutput
print(ord('a'))
97

Given a string of length one, returns an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. This is the inverse of chr() for 8-bit strings.

Syntax:
~x
x & y
x | y
x ^ y
x << n
x >> n

Examples:
CodeOutput
print(~0)           # binary: 000
-1        # binary: 111
print(~-1)          # binary: 111
0         # binary: 000
print(~13)          # binary: 01101
-14       # binary: 10010
print(-1 & -1)      # binary: 111 & 111
-1        # binary: 111
print(14 & 7)       # binary: 01110 & 00111
6         # binary: 00110
print(14 | 7)       # binary: 01110 | 00111
15        # binary: 01111
print(14 ^ 7)       # binary: 01110 ^ 00111
9         # binary: 01001
print(5 << 3)       # binary: 0101 << 3
40        # binary: 0101000
print(23 >> 2)      # binary: 010111 << 2
5         # binary: 0101

These operators all use the underlying twos-complement binary representation of the integral part of the numbers x and y.

  • ~x : bitwise not (negation) of x
  • x & y : bitwise and (conjunction) of x and y
  • x | y : bitwise or (disjunction) of x and y
  • x ^ y : bitwise exclusive or of x and y
  • x << n : bitwise shift left of x by n bits
  • x >> n : bitwise shift right of x by n bits
Operations:
Superclass:
Examples:
Style:
While not encouraged, Booleans can also be used anywhere that numbers can. True and False are then treated as 1 and 0, respectively.

Booleans represent the logical truth values True and False. Expressions that evaluate to Boolean values are especially used as the tests in conditionals (if boolean_expr: …).

Syntax:
True
False

There are only two Boolean constants, True and False. They must be capitalized as shown.

In addition, the following constants are treated like False in a logical expression:

  • None
  • 0
  • 0.0
  • ''
  • []
  • ()
  • {}
  • set([])

All other values are treated like True in logical expressions.

A values of a user-defined class is treated like False if it has a __nonzero__() method that returns False or if it has a __len__() method that returns 0.

Syntax:
bool(x)

Examples:
CodeOutput
print(bool(1))
True
print(bool(2.3))
True
print(bool(0))
False
print(bool([]))
False
print(bool([1, 2, 3]))
True
print(bool(()))
False
print(bool((1, 2, 3)))
True
print(bool(''))
False
print(bool('abc'))
True
print(bool({}))
False
print(bool({1: 2}))
True
print(bool(set([])))
False
print(bool(set([1, 2, 3])))
True
Returns True for any true-like value, and False for any false-like value.
Syntax:
x and y

Examples:
CodeOutput
print(True and True)
True
print(False and True)
False
print(1 and 2)
2
print(0 and 2)
0
Style:
Use only with Boolean expressions.

If x is False or any false-like value, then this expression results in x, otherwise this expression results in y.

xyx and y
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
Syntax:
x or y

Examples:
CodeOutput
print(True or True)
True
print(False or True)
True
print(1 or 2)
1
print(0 or 2)
2
Style:
Use only with Boolean expressions.

If x is False or any false-like value, then this expression results in y, otherwise it results in x.

xyx or y
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Note that in English, the word “or” is used in two different ways. This operation represents “inclusive or” (x or y), where the result is True if at least one argument is True. In contrast, the “exclusive or” (x != y) is True if exactly one argument is True.

Syntax:
not x

Examples:
CodeOutput
print(not True)
False
print(not False)
True
print(not 2)
False
print(not 0)
True
Style:
Use only with Boolean expressions.

If x is False or any false-like value such as 0 or [], then this expression results in True, otherwise it results in False.

xnot x
TrueFalse
FalseTrue
Syntax:
x if b else y

Examples:
CodeOutput
print(1 if True else 2)
1
print(1 if False else 2)
2
Style:
Use only for very simple examples. Conditional statements are generally more readable.

If the Boolean condition b is False is true (or true-like), then the result is x. Otherwise, the result is y.

Syntax:
any(an_iter)

Examples:
CodeOutput
print(any([False, False, False]))
False
print(any([False, True, False]))
True
print(any([]))
False
print(any((0, 3)))
True
print(any('abc'))
True

Returns whether bool(x) is True (or true-like) for any element x in the iterable.

Syntax:
all(an_iter)

Examples:
CodeOutput
print(all([False, True, False]))
False
print(all([True, True, True]))
True
print(all([]))
True
print(all((0, 3)))
False
print(all('abc'))
True

Returns whether bool(x) is True (or true-like) for all elements x in the iterable.

Operations:
Superclasses:
Tutorial:
Examples:

A string is an immutable sequence of characters. Many characters are familiar from what you can type on a keyboard — a letter, a number, a symbol, or a space. The string with zero characters is called the empty string.

Syntax:
"…"
'…'
"""…"""
'''…'''
r"…"
r'…'
r"""…"""
r'''…'''

Examples:
CodeOutput
print("")
      # The empty string.
print('Hello, world.')
Hello, world.
print("Goodbye, cruel world.")
Goodbye, cruel world.
print("It's a beautiful day.")
It's a beautiful day.
print("""This is
a multi-line
string.""")
This is
a multi-line
string.

Typically, string constants are constructed within a matched pair of single or double quotes. A string with double quotes can contain single quotes, often used as apostrophes. Similarly, a string with single quotes can contain double quotes.

Using a pair of triple-single or triple-double quotes also creates a string, but also allows the string to span over multiple lines. These are primarily used as documentation strings to document the purpose of a function, method, or class definition.

Strings can contain ASCII characters.

Strings can contain escape sequences:

\'single quote character
\"double quote character
\\backslash character
\bbackspace character
\fformfeed character
\nnew line character (starts a new line)
\rcarriage return character
\thorizontal tab character (moves to next tab position, which is every eight characters)
\vvertical tab character
\xNNASCII character represented by a hexidecimal number NN

However, raw strings, those preceded by an r, do not recognize escape sequences. Raw strings are typically used for regular expressions.

Syntax:
str(x)

Examples:
CodeOutput
print(str())
    # The empty string
print(str(4859202))
4859202
print(str(True))
True
print(str('abc'))
abc
print(str(None))
None
print(str((1, 2, 3, 4, 5)))
(1, 2, 3, 4, 5)
print(str([1, 2, 3, 4, 5]))
[1, 2, 3, 4, 5]
print(str({1: 'a', 2: 'b', 3: 'c'}))
{1: 'a', 2: 'b', 3: 'c'}
print(str(set([1, 2, 3, 4, 5])))
set([1, 2, 3, 4, 5])
print(str(str))
<class 'str'>
class Silly:    def __init__(self, x):        self.x = xprint(repr(Silly(3)))
<__main__.Silly object>
class Silly:    def __init__(self, x):        self.x = x    def __str__(self):        return 'Silly' + str(self.x)print(str(Silly(3)))
Silly3
See also:
repr() — Emphasizes unambiguity

Returns a string that is a printable representation of object an_obj. The intent is that this string should be human-readable. For built-in types, this is the normal printed representation. For user-defined types, this defaults to a string in angle brackets that includes the type of the object. However, a class can specify what this function returns for its instances by defining a __str__() method.

Syntax:
repr(an_obj)

Examples:
CodeOutput
print(repr([3, 5, 9]))
[3, 5, 9]
class Silly:    def __init__(self, x):        self.x = xprint(repr(Silly(3)))
<__main__.Silly object>
class Silly:    def __init__(self, x):        self.x = x    def __repr__(self):        return 'Silly' + str(self.x)print(repr(Silly(3)))
Silly3
See also:
str() — Emphasizes readability

Returns a string that is a printable representation of object an_obj. The intent is that this string should be unambiguous. For built-in types, this is the normal printed representation. For user-defined types, this defaults to a string in angle brackets that includes the type of the object. However, a class can specify what this function returns for its instances by defining a __repr__() method.

Syntax:
a_str.format(...)

Documentation:
Examples:
CodeOutput
new_style = 'The best instructors are {0} and {1}.'.format('Scott', 'Joe')
print(new_style)
The best instructors are Scott and Joe.
new_style = 'The best instructor is {1}.'.format('Scott', 'Joe')
print(new_style)
The best instructor is Joe.

Return a copy of a_str with each instance of the substring "{n}" replaced by the n+1st argument to format. CodeSkulptor also supports old-style string formatting old-style string formatting. See this example for instances of both new-style and old-style string formatting.

Syntax:
a_str.join([iterable])

Examples:
CodeOutput
print(','.join('abcd'))
a,b,c,d
print(' '.join(['a', 'bc', 'd']))
a bc d
print('zz'.join(('a', 'bc', 'd')))
azzbczzd
print(' '.join({'a': 'x', 'b': 'y'}))
a b
print(' '.join(set(['a', 'b'])))
a b

Returns a string which is the concatenation of the strings in the iterable. The string a_str is concatenated between the other strings as a separator.

Most commonly used to combine a list of strings into a single string.

Syntax:
a_str.capitalize()

Example:
CodeOutput
print('peAr'.capitalize())
Pear

Return a copy of the string a_str with its first character capitalized and the rest lower-cased.

Syntax:
a_str.upper()
a_str.lower()

Examples:
CodeOutput
print('abc123DEF'.upper())
ABC123DEF
print('abc123DEF'.lower())
abc123def

Returns a copy of the string a_str with all the cased characters converted to upper- or lowercase, respectively

Syntax:
a_str.replace(old, new)
a_str.replace(old, new, maxreplace)

Examples:
CodeOutput
print('abcdabcd'.replace('bc', 'f'))
afdafd
print('abcdabcd'.replace('bc', 'f', 1))
afdabcd
print('abcdabcd'.replace('g', 'f'))
abcdabcd
print('aaaaa'.replace('aa', 'f'))
ffa

Returns a copy of the string a_str with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, then the first at most maxreplace occurrences are replaced.

Syntax:
a_str.find(sub)
a_str.find(sub, start)
a_str.find(sub, start, end)
a_str.rfind(sub)
a_str.rfind(sub, start)
a_str.rfind(sub, start, end)
a_str.index(sub)
a_str.index(sub, start)
a_str.index(sub, start, end)
a_str.rindex(sub)
a_str.rindex(sub, start)
a_str.rindex(sub, start, end)

Examples:
CodeOutput
print('abcdabcd'.find('bc'))
1
print('abcdabcd'.find('bc', 3))
5
print('abcdabcd'.find('bc', 3, 6))
5
print('abcdabcd'.rfind('bc'))
5
print('abcdabcd'.rfind('bc', 3))
5
print('abcdabcd'.find('f'))
-1
print('abcdabcd'.rfind('f'))
-1
print('abcdabcd'.find('bc', 6))
-1
print('abcdabcd'.rfind('bc', 6))
-1
print('abcdabcd'.find('bc', 3, 5))
-1

Returns the highest index in the string a_str where substring sub is found, such that sub is contained within a_str[start:end], where start defaults to 0, and end defaults to the length of a_str.

If the substring isn't found, a_str.find() and a_str.rfind() each return -1, while a_str.index() and a_str.rindex() each raise an error.

Syntax:
a_str.partition(sep)
a_str.rpartition(sep)

Examples:
CodeOutput
print('a b c'.partition(' '))
('a', ' ', 'b c')
print('a b c'.rpartition(' '))
('a b', ' ', 'c')
See also:
a_str.split() — Splits multiple times
re.split() — Splits on more general patterns

Splits the string a_str at the first (partition) or last (rpartition) occurrence of substring 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, returns a 3-tuple containing two empty strings, followed by the string itself.

Syntax:
a_str.split()
a_str.split(sep)
a_str.split(sep, maxsplit)

Examples:
CodeOutput
print('a    bc d'.split())
['a', 'bc', 'd']
print('a    bc d'.split(None))
['a', 'bc', 'd']
print('a    bc d'.split(' '))
['a', '', '', '', 'bc', 'd']
print('a    bc d'.split('  '))
['a', '', ' bc d']
print('a    bc d'.split('b'))
['a    ', 'c d']
print('ababbaaaa'.split('a', 2))
['', 'b', 'bbaaaa']
See also:
a_str.partition(), etc. — Splits only once
re.split() — Splits on more general patterns

Returns a list of the words in the string a_str, 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 None, any whitespace string is a separator.

Syntax:
a_str.isdigit()

Examples:
CodeOutput
print(''.isdigit())
False
print('1234'.isdigit())
True
print('1234abc'.isdigit())
False

Returns whether all characters in the string a_str are digits and that there is at least one character in the string.

Syntax:
a_str.center(width)
a_str.center(width, fillchar)
a_str.ljust(width)
a_str.ljust(width, fillchar)
a_str.rjust(width)
a_str.center(width, fillchar)

Examples:
CodeOutput
print('*' + 'abcd'.center(30) + '*')
*             abcd             *
print('abcd'.ljust(30) + '*')
abcd                          *
print('abcd'.rjust(30))
                          abcd
print('*' + 'abcd'.center(30, 'x') + '*')
*xxxxxxxxxxxxxabcdxxxxxxxxxxxxx*
print('abcd'.ljust(30, 'x') + '*')
abcdxxxxxxxxxxxxxxxxxxxxxxxxxx*
print('abcd'.rjust(30, 'x'))
xxxxxxxxxxxxxxxxxxxxxxxxxxabcd

Returns a_str aligned in a string of length width. The fill character defaults to a space. a_str.center() centers the string, a_str.ljust() left justifies it, and a_str.rjust() right justifies it.

These are typically used in simple output formatting to produce fixed-width columns.

Syntax:
a_str.startswith(prefix)

Examples:
CodeOutput
print('silly string'.startswith('sil'))
True
print('silly string'.startswith('ing'))
False
See also:
a_str.endswith() — Checks suffix

Returns whether the string a_str begins with the string prefix.

Syntax:
a_str.endswith(suffix)

Examples:
CodeOutput
print('silly string'.endswith('sil'))
False
print('silly string'.endswith('ing'))
True
See also:
a_str.startswith() — Checks prefix

Returns whether the string a_str ends with the string suffix.

Syntax:
a_str.strip(s)
a_str.strip(s, chars)
a_str.lstrip(s)
a_str.lstrip(s, chars)
a_str.rstrip(s)
a_str.rstrip(s, chars)

Examples:
CodeOutput
print('      cde    fgh    '.strip())
cde    fgh
print('      cde    fgh    '.strip(None))
cde    fgh
print('aaababcdeababfghbaba'.strip('ab'))
cdeababfgh
print('      cde    fgh    '.lstrip())
cde    fgh    
print('aaababcdeababfghbaba'.lstrip('ab'))
cdeababfghbaba
print('      cde    fgh    '.rstrip())
      cde    fgh
print('aaababcdeababfghbaba'.rstrip('ab'))
aaababcdeababfgh

These return a new string like a_str except that leading (a_str.lstrip()), trailing (a_str.rstrip()), or both (a_str.strip()) characters are removed. They remove any characters given in chars, which defaults to any whitespace characters. Also, if chars is None, these also remove whitespace characters.

Operations:
Examples:

A bytes object is an immutable sequence of bytes. This is a representation of binary data that must be interpreted by the program. Often bytes are read from a file and represent its contents Given that they often represent characters, bytes share many operations with strings.

Syntax:
b"…"
b'…'
b"""…"""
b'''…'''

Examples:
CodeOutput
print(b"")
b''      # The empty bytes object.
print(b'Hello, world.')
b'Hello, world.'
print(b"Goodbye, cruel world.")
b'Goodbye, cruel world.'
print(b"It's a beautiful day.")
b'It's a beautiful day.'
print(b"""This is
a multi-line
bytes object.""")
b'This is\na multi-line\nbytes object.'

Bytes constants can be constructed within a matched pair of single or double quotes preceeded by a 'b' character. A bytes object with double quotes can contain single quotes, often used as apostrophes. Similarly, a bytes object with single quotes can contain double quotes.

Using a pair of triple-single or triple-double quotes preceeded by a 'b' character also creates a bytes object, but also allows the bytes object to span over multiple lines.

Bytes objects can contain escape sequences:

\'single quote character
\"double quote character
\\backslash character
\bbackspace character
\fformfeed character
\nnew line character (starts a new line)
\rcarriage return character
\thorizontal tab character (moves to next tab position, which is every eight characters)
\vvertical tab character
\xNNbyte represented by a hexidecimal number NN
Syntax:
bytes(x)

Examples:
CodeOutput
print(bytes())
b''    # The empty bytes object
print(bytes("abc", "ascii"))
b'abc'
print(bytes([64, 65, 66]))
b'@AB'
print(bytes(4))
b''

Returns a bytes object that contains the sequence of bytes represented by the input. A string can be converted into bytes, as long as the optional second argument is provided indicating the character encoding of the string ("ascii" or "utf-8"). Regardless of the encoding, however, all characters in the input string must be ASCII characters. A list of numbers (which all must be between 0 and 255) can be used to indicate the exact sequence of bytes. A single number can be used to create a bytes object with the given number of bytes, each with the value 0.

Syntax:
a_bytes.decode(encoding)
a_bytes.decode(encoding, errors)

Examples:
CodeOutput
print(b"abc".decode("ascii"))
abc
print(bytes([65, 66, 200]).decode("utf-8", "replace"))
AB�
See also:
a_bytes.hex() — Returns a string with hexidecimal values

Returns a string decoded from the given bytes. Possible encodings to use are "utf-8" and "ascii". The optional second argument indicates how to deal with data in the bytes object that are not valid string characters. Possible values are "string" (the default), meaning invalid characters raise an error, "ignore", meaning invalid characters will be ignored and not appear in the output string, and "replace", meaning invalid characters will be replaced with the Unicode replacement character (U+FFFD).

Syntax:
a_bytes.hex()

Example:
CodeOutput
print(b"\xab\xf3\x08".hex())
'abf308'
See also:
a_bytes.decode() — Returns a string with the characters decoded from the given bytes

Return a string containing two hexidecimal digits for each byte.

Syntax:
a_bytes.join([iterable])

Examples:
CodeOutput
print(b','.join([b'a', b'b']))
b'a,b'
print(b' '.join([b'a', b'bc', b'd']))
b'a bc d'
print(b'zz'.join((b'a', b'bc', b'd')))
b'azzbczzd'
print(b' '.join({b'a': 'x', b'b': 'y'}))
b'a b'
print(b' '.join(set([b'a', b'b'])))
b'a b'

Returns a bytes object which is the concatenation of the bytes objects in the iterable. The bytes object a_bytes is concatenated between the other bytes objects as a separator.

Most commonly used to combine a list of bytes objects into a single bytes object.

Syntax:
a_bytes.capitalize()

Example:
CodeOutput
print(b'peAr'.capitalize())
b'Pear'

Return a copy of the bytes a_bytes with its first character capitalized and the rest lower-cased.

Syntax:
a_bytes.upper()
a_bytes.lower()

Examples:
CodeOutput
print(b'abc123DEF'.upper())
b'ABC123DEF'
print(b'abc123DEF'.lower())
b'abc123def'

Returns a copy of the bytes object a_bytes with all the cased characters converted to upper- or lowercase, respectively

Syntax:
a_bytes.replace(old, new)
a_bytes.replace(old, new, maxreplace)

Examples:
CodeOutput
print(b'abcdabcd'.replace(b'bc', b'f'))
b'afdafd'
print(b'abcdabcd'.replace(b'bc', b'f', 1))
b'afdabcd'
print(b'abcdabcd'.replace(b'g', b'f'))
b'abcdabcd'
print(b'aaaaa'.replace(b'aa', b'f'))
b'ffa'

Returns a copy of the bytes object a_bytes with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, then the first at most maxreplace occurrences are replaced.

Syntax:
a_bytes.find(sub)
a_bytes.find(sub, start)
a_bytes.find(sub, start, end)
a_bytes.rfind(sub)
a_bytes.rfind(sub, start)
a_bytes.rfind(sub, start, end)
a_bytes.index(sub)
a_bytes.index(sub, start)
a_bytes.index(sub, start, end)
a_bytes.rindex(sub)
a_bytes.rindex(sub, start)
a_bytes.rindex(sub, start, end)

Examples:
CodeOutput
print(b'abcdabcd'.find(b'bc'))
1
print(b'abcdabcd'.find(b'bc', 3))
5
print(b'abcdabcd'.find(b'bc', 3, 6))
5
print(b'abcdabcd'.rfind(b'bc'))
5
print(b'abcdabcd'.rfind(b'bc', 3))
5
print(b'abcdabcd'.find(b'f'))
-1
print(b'abcdabcd'.rfind(b'f'))
-1
print(b'abcdabcd'.find(b'bc', 6))
-1
print(b'abcdabcd'.rfind(b'bc', 6))
-1
print(b'abcdabcd'.find(b'bc', 3, 5))
-1

Returns the highest index in the bytes object a_bytes where sub is found, such that sub is contained within a_bytes[start:end], where start defaults to 0, and end defaults to the length of a_bytes.

If the bytes aren't found, a_bytes.find() and a_bytes.rfind() each return -1, while a_bytes.index() and a_bytes.rindex() each raise an error.

Syntax:
a_bytes.partition(sep)
a_bytes.rpartition(sep)

Examples:
CodeOutput
print(b'a b c'.partition(b' '))
(b'a', b' ', b'b c')
print(b'a b c'.rpartition(b' '))
(b'a b', b' ', b'c')

Splits the bytes object a_bytes at the first (partition) or last (rpartition) occurrence of substring 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, returns a 3-tuple containing two empty bytes objects, followed by the bytes object itself.

Syntax:
a_bytes.startswith(prefix)

Examples:
CodeOutput
print(b'silly string'.startswith(b'sil'))
True
print(b'silly string'.startswith(b'ing'))
False
See also:
a_bytes.endswith() — Checks suffix

Returns whether the bytes object a_bytes begins with the bytes prefix.

Syntax:
a_bytes.endswith(suffix)

Examples:
CodeOutput
print(b'silly string'.endswith(b'sil'))
False
print(b'silly string'.endswith(b'ing'))
True
See also:
a_bytes.startswith() — Checks prefix

Returns whether the bytes object a_bytes ends with the bytes suffix.

Syntax:
[val0, val1, …]

Examples:
CodeOutput
print([])
[]
print([1, 2, 3, 8, 9])
[1, 2, 3, 8, 9]
print([(1, 2), 'hello', 3, ['a', 'b', 'c']])
[(1, 2), 'hello', 3, ['a', 'b', 'c']]

Lists are constructed with square brackets, separating items with commas.

Syntax:
[val0, val1, …]

Examples:
CodeOutput
print([])
[]
print([1, 2, 3, 8, 9])
[1, 2, 3, 8, 9]
print([(1, 2), 'hello', 3, ['a', 'b', 'c']])
[(1, 2), 'hello', 3, ['a', 'b', 'c']]

Lists are constructed with square brackets, separating items with commas.

Syntax:
list()
list(an_iter)

Examples:
CodeOutput
print(list())
[]
print(list('abc'))
['a' ,'b', 'c']
print(list([1, 2, 3, 4, 5]))
[1, 2, 3, 4, 5]
print(list((1, 2, 3, 4, 5)))
[1, 2, 3, 4, 5]
print(list(set([1, 2, 3, 4])))
[1, 2, 3, 4]
print(list({1: 2, 3: 4}))
[1, 3]
print(list(enumerate(['a', 'b', 'c', 'd'])))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Converts any iterable or iterator into a list. If the argument is already a list, it returns a copy, i.e., a new list with the same elements.

Syntax:
a_list[index] = value

Example:
CodeOutput
numbers = [4, 8, 19, 0]
numbers[1] = 27
print(numbers)
[4, 27, 19, 0]

Mutates the list to now contain the given value at the given index. The index must be within the current range of indices of the list.

Syntax:
range(stop)
range(start, stop)
range(start, stop, step)

Examples:
CodeOutput
print(list(range(5)))
[0, 1, 2, 3, 4]
print(list(range(1, 10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(-10, 100, 20)))
[-10, 10, 30, 50, 70, 90]
print(list(range(100, -10, -20)))
[100, 80, 60, 40, 20, 0]
for i in range(5):
    print(i)
0
1
2
3
4

This is a versatile function to create a generator-like object representing progressions. The step cannot be zero, and it defaults to 1. The start defaults to 0. As a list, the full form consists of a list of integers [start, start + step, start + 2 * step, …]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop.

Note that range does not return a list in Python 3. To create the corresponding list, one should use an expression of the form list(range(...)). range is often used in for loops, as illustrated in the last example above, and does not need to be converted to a list first in order to do so. It provides a mechanism for looping a specific number of iterations.

Syntax:
a_list.append(x)

Examples:
CodeOutput
a_list = [1, 2, 3]
a_list.append(4)
a_list.append([5, 6, 7])
print(a_list)
[1, 2, 3, 4, [5, 6, 7]]
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list1.append([4, 5, 6])
list2.extend([4, 5, 6])
print(list1)
print(list2)
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, 4, 5, 6]

Add item x to the end of the list a_list.

A common mistake is to confuse a_list.append(x) and a_list.extend(x). As shown in the last example above, the former adds one element to the list, while the latter adds a group of elements.

Syntax:
a_list.extend(an_iter)

Examples:
CodeOutput
a_list = [1, 2, 3]
a_list.extend([])
print(a_list)
[1, 2, 3]
a_list = [1, 2, 3]
a_list.extend([4, 5, 6])
a_list.extend((7, 8))
a_list.extend('abc')
a_list.extend({'d': 'e', 'f': 'g'})
[1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c', 'd', 'f']
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list1.append([4, 5, 6])
list2.extend([4, 5, 6])
print(list1)
print(list2)
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, 4, 5, 6]

Add each item from the iterable an_iter onto the end of the list a_list. When the iterable is a list, this is also called concatenation.

A common mistake is to confuse a_list.append(x) and a_list.extend(x). As shown in the last example above, the former adds one element to the list, while the latter adds a group of elements.

Syntax:
a_list.insert(i, x)

Example:
CodeOutput
a_list = ['a', 'b', 'c']
a_list.insert(1, 'x')
print(a_list)
a_list.insert(0, 'y')
print(a_list)
a_list.insert(5, 'z')
print(a_list)
['a', 'x', 'b', 'c']
['y', 'a', 'x', 'b', 'c']
['y', 'a', 'x', 'b', 'c', 'z']

Inserts an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Syntax:
a_list.remove(x)

Example:
CodeOutput
a_list = ['a', 'b', 'c', 'b']
a_list.remove('b')
print(a_list)
['a', 'c', 'b']

Removes the first item from the list whose value is x. It is an error if there is no such item.

Syntax:
a_list.pop([index])

Example:
CodeOutput
a_list = ['a', 'b', 'c']
print(a_list.pop(1))
print(a_list)
b
['a', 'c']

Removes the item at the given index in the list a_list, and returns it. If no index is specified, it defaults to the last item.

Syntax:
a_list.reverse()

Example:
CodeOutput
a_list = [1, 2, 3]
a_list.reverse()
print(a_list)
[3, 2, 1]

Reverses the elements of the list a_list in place.

Syntax:
a_list.sort()
a_list.sort(reverse=rev_bool, key=key_fn)

Examples:
CodeOutput
a_list = [2, 1, 3, 2]
a_list.sort()
print(a_list)
[1, 2, 2, 3]
a_list = [2, 1, 3, 2]
a_list.sort(reverse=True)
print(a_list)
[3, 2, 2, 1]
words = 'This is a test string from Andrew.'.split()
words.sort(key=str.lower
print(words)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

Sorts the items of the list a_list in ascending order in place. I.e., it mutates a_list. It returns None.

By default or when rev_bool is False, the elements are in ascending order. When rev_bool is True, the elements are in descending order. If the elements are of different types, then the ascending or descending ordering is based upon their hash values.

The key argument to sort is a function that is called on each element before sorting. The result of the key function is used in the sort, but the original values in the list are put into the output.

The sort is guaranteed to be stable. Thus, when multiple elements have the same key, their original order is preserved.

Syntax:
[expr for var1 in for_expr1 …]
[expr for var1 in for_expr1 … if if_expr]

Examples:
CodeOutput
print([x*x for x in range(4)])
[0, 1, 4, 9]
print([x+y for x in [1,2,5] for y in [6,2,1] if y!=x])
[7, 3, 8, 3, 11, 7, 6]
See also:
{key_expr: val_expr for … if …} — Dictionary comprehension
{expr for … if …} — Set comprehension
(expr for … if …) — Generator expression

Such a list comprehension iterates over each of for_expr1, …. For each combination of loop variables var1, …, that passes any condition if_expr, the value expr is put in the resulting list.

Operations:
Superclasses:
Tutorial:
Example:
See also:
Lists — Mutable sequences
Strings — Specialized to only containing text

A tuple is an immutable sequence of values of any type. Tuple elements are indexed by sequential integers, starting with zero.

Syntax:
(val0, val1, …)

Examples:
CodeOutput
print(())
()
print((1,))
(1,)
t = 1,
print(t)
(1,)
print((1, 2, 3, 8, 9))
(1, 2, 3, 8, 9)
t = 1, 2, 3, 8, 9
print(t)
(1, 2, 3, 8, 9)
print(((1, 2), 'hello', 3, ['a', 'b', 'c']))
((1, 2), 'hello', 3, ['a', 'b', 'c'])
t = 1, 2, 3
print(t)
(1, 2, 3)

Tuples are constructed by the comma operator, with or without enclosing parentheses. An empty tuple must have the enclosing parentheses. A single item tuple must have a trailing comma.

Syntax:
tuple()
tuple(an_iter)

Examples:
CodeOutput
print(tuple())
()
print(tuple('abc'))
('a' ,'b', 'c')
print(tuple([1, 2, 3, 4, 5]))
(1, 2, 3, 4, 5)
print(tuple((1, 2, 3, 4, 5)))
(1, 2, 3, 4, 5)
print(tuple(set([1, 2, 3, 4])))
(1, 2, 3, 4)
print(tuple({1: 2, 3: 4}))
(1, 3)
print(tuple(enumerate(['a', 'b', 'c', 'd'])))
((0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'))

Converts any iterable into a tuple. If the argument is already a tuple, it returns a copy, i.e., a new tuple with the same elements.

Operations:
Subclasses:
Superclasses:
Tutorial:
Examples:
See also:

A dictionary is a mutable mapping from keys to values. A dictionary with no keys is called an empty dictionary. Dictionaries are also known in some programming languages as associative memories, associative arrays, or hashmaps. Unlike sequences, which are indexed by a range of integers, dictionaries are indexed by keys, which are any hashable values. Thus, dictionaries are also unordered. When printed, iterated upon, or converted into a sequence, its elements will appear in an arbitrary, implementation-dependent order.

Syntax:
{key0: value0, key1: value1, … }

Examples:
CodeOutput
print({})
{}
print({1: 'a', 2: 'b', 9: 'c'})
{1: 'a', 2: 'b', 9: 'c'}
print({1: 'a', (5, 'item'): [100], 'key': {True: 'hello', -9: 0}})
{1: 'a', (5, 'item'): [100], 'key': {True: 'hello', -9: 0}}

A dictionary is an unordered collection of key: value pairs, with each key in a dictionary being distinct.

Syntax:
dict()
dict(an_iter)

Examples:
CodeOutput
print(dict())
{}
print(dict([(1, 'a'), (2, 'b'), (3, 'c')]))
{1: 'a', 2: 'b', 3: 'c'}
print(dict(((1, 'a'), (2, 'b'), (3, 'c'), (3, 'd'))))
{1: 'a', 2: 'b', 3: 'd'}
print(dict(set([(1, 'a'), (2, 'b'), (3, 'c')])))
{1: 'a', 2: 'b', 3: 'c'}
print(dict({1: 'a', 2: 'b', 3: 'c'}))
{1: 'a', 2: 'b', 3: 'c'}
print(dict(enumerate(['a', 'b', 'c', 'd'])))
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}

Returns a new dictionary with the data from an_iter. The iterable or iterator an_iter must consist of pairs of a valid key (i.e., of immutable type) and value. If any key occurs multiple times, then the last value encountered for that key will be in the resulting dictionary. If an_iter is already a dictionary, it returns a copy, i.e., a new dictionary with the same elements.

Syntax:
a_dict[key]
a_dict.get(key)
a_dict.get(key, value)

Examples:
CodeOutput
print({1: 'a', 2: 'b', 3: 'c'}[2])
b
print({1: 'a', 2: 'b', 3: 'c'}.get(2))
b
print({1: 'a', 2: 'b', 3: 'c'}.get(7))
None
print({1: 'a', 2: 'b', 3: 'c'}.get(7, 'not here'))
not here
Style:
Avoid using a_dict.get(key) without a default.

If the key is in the dictionary, these each return the value associated with the given key the dictionary a_dict.

If the key is not in the dictionary, then a_dict[key] raises a KeyError error. However, a_dict.get(key) returns value if provided, and None otherwise.

Syntax:
a_dict[key] = value
a_dict.__setitem__(key, value)
a_dict.setdefault(key)
a_dict.setdefault(key, value)

Examples:
CodeOutput
d = {1: 'a', 2: 'b', 3: 'c'}
d[3] = 'd'
d[4] = 'e'
print(d)
{1: 'a', 2: 'b', 3: 'd', 4: 'e'}
d = {1: 'a', 2: 'b', 3: 'c'}
d.setdefault(3, 'd')
d.setdefault(4, 'e')
print(d)
{1: 'a', 2: 'b', 3: 'c', 4: 'e'}
Style:
Avoid using a_dict.__setitem__().

a_dict[key] = value and a_dict.__setitem__() each mutate the dictionary a_dict so that the given key now maps to the given value.

a_dict.setdefault(key, value) similarly mutates the dictionary, but only if the key does not exist in the dictionary. The value defaults to None.

Syntax:
a_dict.pop(key)
a_dict.pop(key, default)

Examples:
CodeOutput
d = {1: 'a', 2: 'b', 3: 'c'}
print(d.pop(1))
print(d)
a
{2: 'b', 3: 'c'}
d = {1: 'a', 2: 'b', 3: 'c'}
print(d.pop(1, 'xyz'))
print(d)
a
{2: 'b', 3: 'c'}
d = {1: 'a', 2: 'b', 3: 'c'}
print(d.pop(4))
print(d)
Line 2: KeyError: 4
d = {1: 'a', 2: 'b', 3: 'c'}
print(d.pop(4, 'xyz'))
print(d)
xyz
{1: 'a', 2: 'b', 3: 'c'}

If key is a key in the dictionary, this removes it from the dictionary and returns its value. The value default is ignored in this case.

If key is not a key in the dictionary, this returns the value default. If no default is provided, a KeyError is raised.

Syntax:
a_dict.items()

Examples:
CodeOutput
print({1: 'a', 2: 'b', 3: 'c'}.items())
[(1, 'a'), (2, 'b'), (3, 'c')]
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
for key, value in sample_dict.items():
    print(key, 'maps to', value)
1 maps to a
2 maps to b
3 maps to c

Returns an iterable of (key, value) pairs, for all the keys in dictionary a_dict.

A common usage is to loop over all key/value pairs in a dictionary, as in the last example above.

Syntax:
a_dict.keys()

Example:
CodeOutput
print({1: 'a', 2: 'b', 3: 'c'}.keys())
[1, 2, 3]

Returns an iterable consisting of the keys in dictionary a_dict.

While you can test if something is a dictionary key explicitly, like key in a_dict.keys(), the simpler expression key in a_dict is equivalent. The same applies to for-loops.

Syntax:
a_dict.values()

Examples:
CodeOutput
print({1: 'a', 2: 'b', 3: 'c'}.values())
['a', 'b', 'c']
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
for value in sample_dict.values():
    print(value, 'is a value in the dictionary')
a is a value in the dictionary
b is a value in the dictionary
c is a value in the dictionary

Returns an iterable consisting of the values in dictionary a_dict.

A common usage is to loop over all values in a dictionary, as in the last example above.

Syntax:
a_dict.clear()

Example:
CodeOutput
d = {1: 'a', 2: 'b', 3: 'c'}
d.clear()
print(d)
{}

Mutates a dictionary to be empty. Returns None.

Syntax:
a_dict.update(another_dict)

Example:
CodeOutput
d = {1: 'a', 2: 'b', 3: 'c'}
d.update({3: 'd', 4: 'e'})
print(d)
{1: 'a', 2: 'b', 3: 'd', 4: 'e'}

Mutates a_dict to have the key/value pairs in another_dict. Returns None.

Syntax:
{key_expr: val_expr for var1 in for_expr1 …}
{key_expr: val_expr for var1 in for_expr1 … if if_expr}

Examples:
CodeOutput
print({x: x*x for x in range(4)})
{0: 0, 1: 1, 2: 4, 3: 9}
print({(x,y): x+y for x in [1,2,5] for y in [6,2,1] if y!=x})
{(1, 6): 7, (1, 2): 3, (2, 6): 8, (2, 1): 3, (5, 6): 11, (5, 2): 7, (5, 1): 6}
See also:
[expr for … if …] — List comprehension
{expr for … if …} — Set comprehension
(expr for … if …) — Generator expression

Such a dictionary comprehension iterates over each of for_expr1, …. For each combination of loop variables var1, …, that passes any condition if_expr, the key/value pair key_expr:val_expr is put in the resulting dictionary.

  • dict() with keyword arguments
  • a_dict.copy()
  • a_dict.popitem()
Syntax:
{expr for var1 in for_expr1 …}
{expr for var1 in for_expr1 … if if_expr}

Examples:
CodeOutput
print({x*x for x in range(4)})
set([0, 1, 4, 9])
print({x+y for x in [1,2,5] for y in [6,2,1] if y!=x])
set([3, 6, 7, 8, 11])
See also:
[expr for … if …] — List comprehension
{key_expr: val_expr for … if …} — Dictionary comprehension
(expr for … if …) — Generator expression
Syntax:
{value0, value1, …}

Examples:
CodeOutput
print({1, 2, 3, 4, 5, 3, 5})
set([1, 2, 3, 4, 5])
print({'abc', 'def'})
set(['abc', 'def'])
See also:
set — Old style of set constants
Style:
New style of set constants. Doesn't allow representation of empty set.

Returns a new set with the listed values.

Syntax:
set()
set(an_iter)

Examples:
CodeOutput
print(set())
set([])
print(set('abc'))
set(['a' ,'b', 'c'])
print(set([1, 2, 3, 4, 5, 3, 5]))
set([1, 2, 3, 4, 5])
print(set((1, 2, 3, 4, 5)))
set([1, 2, 3, 4, 5])
print(set(set([1, 2, 3, 4])))
set([1, 2, 3, 4])
print(set({1: 2, 3: 4}))
set([1, 3])
print(set(enumerate(['a', 'b', 'c', 'd'])))
set([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')])
See also:
Sets-constants — New style of set constants
Style:
Old style of set constants

Returns a new set with the values from iterable or iterator an_iter. If the argument is already a set, it returns a copy, i.e., a new set with the same elements.

Syntax:
a_set.union(an_iter)

Example:
CodeOutput
print(set([1, 2, 3, 4, 5]).union(set([5, 6, 7])))
set([1, 2, 3, 4, 5, 6, 7])

Returns the union of set a_set and the set of elements in iterable an_iter.

Syntax:
a_set.intersection(an_iter)

Example:
CodeOutput
print(set([1, 2, 3, 4, 5]).intersection(set([5, 6, 7])))
set([5])

Returns the intersection of set a_set and the set of elements in iterable an_iter.

Syntax:
a_set.difference(an_iter)

Example:
CodeOutput
print(set([1, 2, 3, 4, 5]).difference(set([5, 6, 7])))
set([1, 2, 3, 4])

Returns a set with all elements from set a_set that are not in iterable an_iter.

Syntax:
a_set.symmetric_difference(anInter)

Example:
CodeOutput
print(set([1, 2, 3, 4, 5]).symmetric_difference(set([5, 6, 7])))
set([1, 2, 3, 4, 6, 7])

Returns a set with all elements that are in exactly one of set a_set and iterable an_iter.

Syntax:
a_set.update(an_iter)

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
s.update(set([5, 6, 7]))
print(s)
set([1, 2, 3, 4, 5, 6, 7])

Mutates a_set to be the union of set a_set and the set of elements in iterable an_iter. Returns None.

Syntax:
a_set.intersection_update(an_iter)

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
s.intersection_update(set([5, 6, 7]))
print(s)
set([5])

Mutates a_set to be the intersection of set a_set and the set of elements in iterable an_iter. Returns None.

Syntax:
a_set.difference_update(an_iter)

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
s.difference_update(set([5, 6, 7]))
print(s)
set([1, 2, 3, 4])

Mutates a_set to be the set difference of set a_set and the set of elements in iterable an_iter. Returns None.

Syntax:
a_set.symmetric_difference_update(an_iter)

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
s.symmetric_difference_update(set([5, 6, 7]))
print(s)
set([1, 2, 3, 4, 6, 7])

Mutates a_set to be a set with all elements that are in exactly one of set a_set and iterable an_iter. Returns None.

Syntax:
a_set.add(x)

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
s.add(5)
print(s)
s.add(6)
print(s)
set([1, 2, 3, 4, 5])
set([1, 2, 3, 4, 5, 6])

Adds element x to the set a_set. Returns None.

Syntax:
a_set.remove(x)
a_set.discard(x)

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
s.remove(5)
print(s)
s.discard(7)
print(s)
s.discard(3)
print(s)
set([1, 2, 3, 4])
set([1, 2, 3, 4])
set([1, 2, 4])

Removes element x from set a_set. If element x is not in a_set, a_set.remove raises an error, while a_set.discard does not. Returns None.

Syntax:
a_set.pop()

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
print(s.pop())
print(s)
1
set([2, 3, 4, 5])

Removes and returns an arbitrary element from set a_set. Raises an error if there are no elements to remove.

Syntax:
a_set.issubset(an_iter)

Examples:
CodeOutput
s = set([2, 9, 7, 1]
print(s.issubset(s))
True
print(set([2, 9, 7, 1]).issubset(set([1, 7])))
False
print(set([2, 9, 7, 1]).issubset(set([1, 2, 3, 4])))
False
print(set([2, 9, 7, 1]).issubset(set([1, 2, 3, 4, 5, 6, 7, 8, 9])))
True
print(set([2, 9, 7, 1]).issubset([1, 2, 7, 9])
True

Returns whether the set a_set is a subset of the set of elements in iterable an_iter.

Syntax:
a_set.issuperset(an_iter)

Examples:
CodeOutput
s = set([2, 9, 7, 1]
print(s.issuperset(s))
True
print(set([2, 9, 7, 1]).issuperset(set([1, 7])))
True
print(set([2, 9, 7, 1]).issuperset(set([1, 2, 3, 4])))
False
print(set([2, 9, 7, 1]).issuperset(set([1, 2, 3, 4, 5, 6, 7, 8, 9])))
False
print(set([2, 9, 7, 1]).issuperset([1, 2, 7, 9])
True

Returns whether the set a_set is a superset of the set of elements in iterable an_iter.

Syntax:
a_set.copy()

Example:
CodeOutput
s = set([1, 2, 3, 4, 5])
t = s.copy()
print(s == t)
print(s is t)
True
False

Makes a new set with the same elements as a_set.

  • |
  • &
  • -
  • ^
  • |=
  • &=
  • -=
  • ^=
  • s.clear()
Operations:
Superclass:
Examples:

A function is a parameterized section of code. A method is simply a function which is an attribute of an object, i.e., defined as part of a class. Functions and methods are values themselves. (However, CodeSkulptor does not yet consider built-in functions to be values.)

Syntax:
def a_func(var0, var1, …): …

Examples:
CodeOutput
def is_even(n):
    '''Returns a Boolean indicating whether n is even.'''
    return n % 2 == 0

print(is_even)
print(is_even(2))
<function is_even>
True
def median_3(a, b, c):
    '''Returns the median (middle) of the three arguments.'''
    if a <= b:
        if b <= c:
            return b
        elif a <= c:
            return c
        else:
            return a
    else:
        if a < c:
            return a
        elif b < c:
            return c
        else:
            return b

print(median_3(5, 9, 2))
5
def swap_list_elts(l, index1, index2):
    '''Swaps l[index1] and l[index2]'''
    l[index1], l[index2] = l[index2], l[index1]

l = ['a', 'b', 'c', 'd']
print(swap_list_elts(l, 1, 3))
print(l)
None
['a', 'd', 'c', 'b']
def add2(n):
    '''Returns the given value plus 2.'''
    return n + 2

print(map(add2, [1, 3, 5]))
[3, 5, 7]
Tutorial:

Creates a function named by a_func. When applied to arguments, the code in the function body is run until a return statement is reached or the end of the code is reached. In the former case, the function returns the value specified in the return, while in the latter case, the function returns None.

To be distinct from a generator function the body must not contain yield statements.

For good style, each named function should also have a documentation string (docstring) immediately after its header, as illustrated in the examples.

Syntax:
lambda var1, var2, …: expr

Examples:
CodeOutput
is_even = lambda n : n % 2 == 0
print(is_even)
print(is_even(2))
<function <lambda>>
True
print(map(lambda n: n + 2, [1, 3, 5]))
[3, 5, 7]
Tutorial:

Anonymous functions are simplified forms of function definitions. First, they do not have a name. Second, the parameter list is not in parentheses. And third, the function body is just a single expression, which is implicitly returned. This simplicity is convenient especially when the function is simply passed as an argument, as in the last example above.

  • Built-in functions and methods are not values.
  • Keyword arguments are not supported.
  • classmethod()
  • staticmethod()
  • a_func.func_doc
  • a_func.__doc__
  • a_func.func_name
  • a_func.__name__
  • a_func.__module__
  • a_func.func_defaults
  • a_func.func_code
  • a_func.func_globals
  • a_func.func_dict
  • a_func.func_closure
Operations:
Superclasses:

Generators are a kind of iterator that can be defined like functions. A generator function looks just like a regular function, except that it uses yield instead of return.

Syntax:
(expr for var1 in for_expr1 …)
(expr for var1 in for_expr1 … if if_expr)

Examples:
CodeOutput
print((x*x for x in range(4)))
<generator object <genexpr>>
print((x*x for x in range(4)).next())
0
print(list(x*x for x in range(4)))
[0, 1, 4, 9]
print(list(x+y for x in [1,2,5] for y in [6,2,1] if y!=x))
[7, 3, 8, 3, 11, 7, 6]
See also:
[expr for … if …] — List comprehension
{key_expr: val_expr for … if …} — Dictionary comprehension
{expr for … if …} — Set comprehension

Such a generator expression iterates over each of for_expr1, …. For each combination of loop variables var1, …, that passes any condition if_expr, the value expr is put in the resulting list.

Syntax:
def a_genfunc(var0, var1, …): … yield … …

Example:
CodeOutput
def squares(n):
    '''Yields the squares from 0 to n-1 squared.'''
    for i in range(n):
        yield i * i

g = squares(4)
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())
0
1
4
9
See also:
def … return — Function definition
Style:
A generator function should have a documentation string (docstring) immediately after its header, as illustrated in the example.

Creates a generator function named by an_iter. When applied to arguments, the code in the function body is encapsulated and returned as a generator, a type of iterator. Each time the __next__(), method is applied to the resulting generator, the code is run until the next yield expression, and the yield expression's value is returned from that method call. Thus, the creation of the generator does not wait for all of its elements to be generator, and the generator could even represent an infinite number of elements.

To be distinct from a function definition, the body must contain yield statements, not return statements.

Syntax:
a_gen.send(val)

Examples:
CodeOutput
def foo():
    x = yield 1
    print('Yielded:', x)
    yield 2

bar = foo()
print(bar.__next__())
print(bar.send('Hi!'))
1
Yielded: Hi!
2
def add1genf(n):
    while n != None:
        print('Before:', n)
        n = yield n + 1
        print('After:', n)

add1gen = add1genf(10)
print('---')
print(add1gen.send('This first value is ignored.'))
print('---')
print(add1gen.send(3))
print('---')
print(add1gen.send(17))
---
Before: 10
11
---
After: 3
Before: 3
4
---
After: 17
Before: 17
18

Like the __next__() method, it runs the generator code from where it started (on the first call) or last yielded, stopping at the next yield expression. It returns the value of the yield expression. It also sends the value val back to the generator's yield expression.

  • a_gen.throw()
  • a_gen.close()
Operations:
Superclasses:
See also:
codeskulptor.file2url — Abbreviating standard URLs

This module contains functions for obtaining input data from the web. Currently, CodeSkulptor's implementation of this module supports input only, not output, and only from a a CodeSkulptor-affiliated data storage site. To use these operations, first import the module with import urllib.request.

File objects represent open files. A file object keeps track of the current position in the file. Each read operation gets data starting at this position and advances the position to the end of the returned data. CodeSkulptor only supports obtaining an open file via urllib.request.urlopen().

Syntax:
a_file.read()
a_file.read(size)

Examples:
CodeOutput
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.read())
b'This is line one.\nThis is line two.\nThis is line three.\n'
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.read(7))
b'This is'
See also:
a_file.readline() — Reads one line
a_file.readlines() — Reads multiple lines

With no argument or a negative size argument, this returns a bytes object containing the rest of the file.

With a non-negative size argument, this returns a bytes object containing the next at-most size bytes (characters) of the file. It returns fewer bytes than requested only when there are fewer bytes remaining in the file.

Syntax:
a_file.readline()
a_file.readline(size)

Examples:
CodeOutput
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.readline())
b'This is line one.\n'
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.read(7))
print(a_file.readline())
b'This is'
b' line one.\n'
See also:
a_file.read() — Reads
a_file.readlines() — Reads multiple lines

With no argument or a negative size argument, this returns a bytes object containing the rest of the current line in the file. I.e., it returns all the characters up to and including the next newline character ' ' or end of file.

With a non-negative size argument, this returns a bytes object containing the next at-most size bytes (characters) of the file. It returns fewer bytes than requested only when there are fewer bytes remaining in the file.

Syntax:
a_file.readlines()
a_file.readlines(sizehint)

Examples:
CodeOutput
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.readlines())
[b'This is line one.\n', b'This is line two.\n', b'This is line three.\n']
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.readline())
print(a_file.readlines())
b'This is line one.\n'
[b'This is line two.\n', b'This is line three.\n']
See also:
a_file.read() — Reads
a_file.readline() — Reads one line

Reads the rest of the file, separating its content into a sequence of lines ending in the newline character '\n'. This sequence is returned as a list of bytes objects.

The number sizehint is an estimate of how many bytes remain in the file. Its value does not affect the result.

  • list() on file objects
  • a_file.close()
  • a_file.fileno()
  • a_file.flush()
  • a_file.isatty()
  • a_file.seek()
  • a_file.tell()
  • a_file.truncate()
  • a_file.write()
  • a_file.writelines()
  • a_file.xreadlines()
  • a_file.closed
  • a_file.encoding
  • a_file.errors
  • a_file.mode
  • a_file.name
  • a_file.newlines
  • a_file.softspace
Operations:
Superclasses:
Syntax:
enumerate(an_iter)
enumerate(an_iter, start)

Examples:
CodeOutput
print(enumerate(['a', 'b', 'c', 'd']))
<enumerate object>
print(list(enumerate(['a', 'b', 'c', 'd'])))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
print(list(enumerate(['a', 'b', 'c', 'd'], 5)))
[(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')]

Returns an enumeration object, a type of iterator. Each element of the iterator is a pair of a number and an element from the given iterable or iterator an_iter. The first number is start (or the default zero), and successive numbers are each one greater than the previous.

Operations:
Subclasses:
Superclasses:

Iterators are a kind of iterable, and thus support iteration or looping — e.g., for x in an_iter. Such a loop implicitly calls an_iter.__next__() repeatedly to get each element from the iterator, thus exhausting the elements in the iterator. Similarly, calling functions such as list() on an iterator will implicitly loop through and exhaust the iterator.

Syntax:
next(an_iter)
next(an_iter, value)
an_iter.__next__()

Examples:
CodeOutput
i = enumerate(['a', 'b', 'c'])
print(next(i))
print(next(i))
print(next(i, 0))
print(next(i, 0))
(0, 'a')
(1, 'b')
(2, 'c')
0
def foo():
    x = yield 1
    print('Yielded:', x)
    yield 2

bar = foo()
print(bar.__next__())
print(bar.__next__())
1
Yielded: None
2
Style:
Avoid using an_iter.__next__().

Returns the next element of the iterator and removes it from the iterator.

If the iterator has no next element, then an error is raised, except when using next(an_iter, value), in which case the value is returned.

For a generator defined by a generator function, these operations' behavior can be described in more detail. The generator's code runs from where it started (on the first call) or last yielded, stopping at the next yield expression. The generator returns the value of the yield expression. The operation also sends the value None back to the generator's yield expression.

  • an_iter.__next__() incorrectly does not raise an error if the iterator is empty.
  • an_iter.__iter__()
  • iter()
Operations:
Subclasses:
Superclasses:

Sequences are ordered collections of data. Their elements can be indexed by integers indicating positions.

Syntax:
seq1 + seq2

Examples:
CodeOutput
print('hello' + ' ' + 'world!')
hello world!
print([1, 2, 3] + [4, 5, 6])
[1, 2, 3, 4, 5, 6]
print(('a', 'b', 'c') + (1, 2) + ([2, 3, 4], [1]))
('a', 'b', 'c', 1, 2, [2, 3, 4], [1])

Returns the concatenation of seq1 and seq2. I.e., it returns a new sequence that contains the contents of the first sequence, then the contents of the second sequence. The two sequences must be of the same type, and the result is of the same type.

Syntax:
a_seq * n
n * a_seq

Examples:
CodeOutput
print('hello' * 2)
hellohello
print(['a', 'b', 'c'] * 3)
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
print((1, 2, 3, 4) * 4)
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
x = [[1, 2]] * 3
print(x)
x[0][0] = 3
print(x)
[[1, 2], [1, 2], [1, 2]]
[[3, 2], [3, 2], [3, 2]]

Returns the concatenation of n copies of a_seq. The copies are “shallow” in that if the sequence contains compound objects, the contents of those objects are not copied. In the last example above, each of the sub-lists [1, 2] is the same list; they are not just lists that look alike.

Syntax:
a_seq[i]
a_seq.__getitem__(i)

Examples:
CodeOutput
print('abcde'[2])
c
print((8, 2, 4, 0)[3])
0
print([8, 2, 4, 0][-3])
2
Style:
Avoid using a_seq.__getitem__().

Returns the item in sequence a_seq at integer index i. Given a non-negative index, it starts counting from index 0 on the left. Given a negative index, it starts counting from index -1 on the right.

Syntax:
a_seq[i:j]
a_seq[i:j:k]

Examples:
CodeOutput
print('abcde'[1:3])
bc
print((8, 2, 4, 0)[1:-1])
(2, 4)
print([8, 2, 4, 0][1:])
[2, 4, 0]
print('abcde'[1:4:2])
bd
print((8, 2, 4, 0)[1::1])
(2, 4, 0)
print([8, 2, 4, 0][::-1])
[0, 4, 2, 8]

Returns a new sequence (a “slice”) of the items in the sequence a_seq starting from integer index i up to integer index j-1, incrementing indices by integer k.

Omitting index i starts the sequence at the leftmost position. Omitting index j ends the sequence at the rightmost position. The step k defaults to 1, i.e., including each element in the indexed range from left to right.

The new sequence is of the same type as a_seq.

Syntax:
a_seq.index(val)
a_seq.index(val, start)
a_seq.index(val, start, end)

Examples:
CodeOutput
print(['a', 'b', 'c', 'b', 'a', 'c'].index('c'))
2
print(('a', 'b', 'c', 'b', 'a', 'c').index('c'))
2
print('abcbac'.index('c'))
2
print('abcbac'.index('ba'))
3
print(['a', 'b', 'c', 'b', 'a', 'c'].index('c', 3))
5
print(('a', 'b', 'c', 'b', 'a', 'c').index('c', 3))
5
print('abcbac'.index('c', 3))
5
See also:
a_str.find(), etc. — Similar methods

Returns the index in the sequence a_seq[start:end] of the first item whose value is val. If a_seq is a string, then val can be a string of any length, not just a single character. By default, start is 0, and end is the length of the string. It is an error if there is no such item.

A common mistake is to use it to find the next item:

for item in my_list:   next_item = my_list[my_list.index(item) + 1]   print(item, next_item)
This doesn't accomplish the intended goal when the list contains duplicates, since my_list.index(item) finds the first instance of item.

Syntax:
a_seq.count(val)
a_str.count(val, start)
a_str.count(val, start, end)

Examples:
CodeOutput
print(['a', 'b', 'c', 'b', 'a', 'c'].count('b'))
2
print(('a', 'b', 'c', 'b', 'a', 'c').count('b'))
2
print('abcbac'.count('c'))
2
print('abcbac'.count('cb'))
1
print('abcbac'.count('b', 3))
1
print('abcbac'.count('b', 2, 3))
0

Returns the number of times the value val appears in the sequence a_seq.

For strings only, there are two differences in the method. Additional arguments limit the part of the string to search. Also, val can be a string of any length, not just a single character. Thus, it returns the number of times val is a substring in a_str[start:end]. By default, start is 0, and end is the length of the string.

Operations:
Subclasses:
Superclass:

Iterables are collections of data that allow iteration or looping — e.g., for x in an_iter.

Syntax:
val in an_iter

Examples:
CodeOutput
print(8 in [1, 2, 3, 4, 5, 6, 7])
False
print('c' in 'abcde')
True
print((1,3) in ('a', 3, 4, (1,2), 'hello'))
False
print(3 in {1: 'a', 2: 'b', 3: 'c'})
True
print(3 in {'a': 1, 'b': 2, 'c: 3})
False
print(8 in set([1, 2, 3, 4, 5, 6, 7]))
False
See also:
not in — Complement

Returns True if value val is in the iterable, otherwise returns False.

Syntax:
val not in an_iter

Examples:
CodeOutput
print(8 not in [1, 2, 3, 4, 5, 6, 7])
True
print('c' not in 'abcde')
False
print((1,3) not in ('a', 3, 4, (1, 2), 'hello'))
True
print(3 not in {1: 'a', 2: 'b', 3: 'c'})
False
print(3 not in {'a': 1, 'b': 2, 'c': 3})
True
print(8 not in set([1, 2, 3, 4, 5, 6, 7]))
True
See also:
in — Complement

Returns True if value val is not in the iterable, otherwise returns False.

Syntax:
len(an_iter)

Examples:
CodeOutput
print(len(''))
0
print(len([2, 35, -2, 12]))
4
print(len((2, 35, -2, 12)))
4
print(len({1: 2, 3: 4}))
2
print(len(set([2, 35, -2, 12])))
4

Returns the number of items in the iterable.

Syntax:
sum(an_iter)
sum(an_iter, start)

Examples:
CodeOutput
print(sum([10, 20, 30]))
60
print(sum((10, 20, 30)))
60
print(sum({1: 10, 2: 20}))
3
print(sum(set([10, 20, 30)])))
60
print(sum([10, 20, 30], 2))
62

Returns the sum of start, which defaults to 0, and the numbers in the iterable.

Syntax:
max(val1, val2, …)
max(an_iter)

Examples:
CodeOutput
print(max(2, 35, -2, 12))
35
print(max('c', 'x', 'cat', 'father'))
x
print(max([2, 35, -2, 12]))
35
print(max(['c', 'x', 'cat', 'father']))
x
print(max((2, 35, -2, 12)))
35
print(max({1: 2, 3: 4}))
3
print(max(set([2, 35, -2, 12])))
35

Given multiple arguments, it returns the argument with the maximum value. Given a single iterable argument (other than a string), it returns the item in the iterable with maximum value.

Syntax:
min(val1, val2, …)
min(an_iter)

Examples:
CodeOutput
print(min(2, 35, -2, 12))
-2
print(min('c', 'x', 'cat', 'father'))
c
print(min([2, 35, -2, 12]))
-2
print(min(['c', 'x', 'cat', 'father']))
c
print(min((2, 35, -2, 12)))
-2
print(min({1: 2, 3: 4}))
1
print(min(set([2, 35, -2, 12])))
-2

Given multiple arguments, it returns the argument with the minimum value. Given a single iterable argument (other than a string), it returns the item in the iterable with minimum value.

Syntax:
zip(iter1, iter2, …)

Examples:
CodeOutput
print(zip('abcd', '1234', (5, 6, 7, 8)))
[('a', '1', 5), ('b', '2', 6), ('c', '3', 7), ('d', '4', 8)]
print(zip([1, 2, 3, 4], ['a', 'b', 'c']))
[(1, 'a'), (2, 'b'), (3, 'c')]
print(zip({1: 2, 3: 4}, set([5, 6])))
[(1, 5), (3, 6)]
print(zip([1, 2, 3]))
[(1,), (2,), (3,)]
print(zip())
[]
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['z', 'y', 'x', 'w', 'v']
for letter1, letter2 in zip(list1, list2):
    print(letter1 + letter2)
az
by
cx
dw
ev
zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')]
first_elts, second_elts = zip(*zipped_list)
print(first_elts)
print(second_elts)
[1, 2, 3]
['a', 'b', 'c']

Returns a list of tuples, where the ith tuple contains the ith element of each iterable. For intuition, picture the action of matching up the two sides of a standard zipper. The result's length is that of the shortest argument. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

A common usage of zip() is to iterate over two same-length lists (or other iterables) in lock-step, as shown in the next-to-last example above.

Unzipping: There is no built-in function to do the opposite of zip(). However, one approach is to use function argument unpacking along with zip() to group the desired elements, as shown in the last example above.

Syntax:
sorted(an_iter)
sorted(an_iter, reverse=rev_bool, key=key_fn)

Examples:
CodeOutput
print(sorted('blue'))
['b', 'e', 'l', 'u']
print(sorted([2, 1, 3, 2]))
[1, 2, 2, 3]
print(sorted([2, 1, 3, 2], reverse=True))
[3, 2, 2, 1]
print(sorted('This is a test string from Andrew'.split(), key=str.lower))
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
See also:
a_list.sort() — Sort a list in-place

Returns a list of the elements of the iterable in sorted order.

By default or when rev_bool is False, the elements are in ascending order. When rev_bool is True, the elements are in descending order. If the elements are of different types, then the ascending or descending ordering is based upon their hash values.

The key argument to sorted is a function that is called on each element before sorting. The result of the key function is used in the sort, but the original values in the list are put into the output.

The sort is guaranteed to be stable. Thus, when multiple elements have the same key, their original order is preserved.

Syntax:
map(function, an_iter)

Example:
CodeOutput
def square(n):
    return n * n

print(map(square, [3, 7, 1]))
[9, 49, 1]

Applies the user-defined function to the elements of the iterable an_iter, and returns a list of the results. The ith element of the returned list is function(an_iteriter1[i], &hellip).

Syntax:
filter(function, an_iter)

Examples:
CodeOutput
def is_positive(n):
    return n > 0

print(filter(is_positive, [3, -7, 1]))
[3, 1]
def is_positive(n):
    return n > 0

print(filter(is_positive, (3, -7, 1)))
(3, 1)
def is_aorb(x):
    return x == 'a' or x == 'b'

print(filter(is_aorb, 'acdba'))
'aba'
def is_positive(n):
    return n > 0

print(filter(is_positive, set([3, -7, 1])))
[1, 3]
print(filter(None, [set(), 3, {}, 0, False, '', -1, []]))
[3, -1]

Applies the user-defined function to the elements of the iterable an_iter, and returns a sequence of those elements for which the function returns a true-like value. If the function is None, then the function is taken to be the identity function — i.e., it returns a sequence of those elements which are true-like values.

If the iterable an_iter is a sequence, then the returned value is of that same type, otherwise the returned value is a list.

Syntax:
reduce(function, an_iter)
reduce(function, an_iter, initializer)

Examples:
CodeOutput
def add(x, y):
    return x + y

print(reduce(add, [3, -7, 1]))
-3
def add(x, y):
    return x + y

print(reduce(add, (3, -7, 1), 12))
9
def maximum(x, y):
    if x >= y:
        return x
    else:
        return y

print(reduce(maximum, 'acdba', 'a'))
'd'
def maximum(x, y):
    if x >= y:
        return x
    else:
        return y

print(reduce(maximum, 'acdba', 'z'))
'z'
def second(x, y):
    return y

print(reduce(second, [1, 2, 3, 4, 5]))
5

Combines the elements of the iterable an_iter by repeatedly applying the two-argument function to an accumulator and each respective element in turn. Without an initializer, if the iterable has no elements, then an error is raise, and if the iterable has one element, that element is returned. With an initializer, if the iterable has no elements, the initializer is returned.

Without an initializer, this is equivalent to

def reduce(function, an_iter):
    started = False
    result = False

    if not an_iter:
        raise TypeError('reduce() of empty sequence with no initial value')

    for element in an_iter:
        if not started:
            result = element
            started = True
        else:
            result = function(result, element)

With an initializer, this is equivalent to

def reduce(function, an_iter, initializer):
    result = initializer

    for element in an_iter:
        result = function(result, element)
  • max() and min() with key argument.
  • map(), filter(), and reduce() on built-in functions.
  • __iter__()
  • iter()
Operations:
Subclasses:
Syntax:
x < y
x <= y
x > y
x >= y
x == y
x != y
x is y
x is not y

Examples:
CodeOutput
print(2 < 3)
True
print(False < True)
True
print(2 < 2)
False
print('abc' <= 'ad')
True
print(2 <= 2)
True
print([1, 3] > [1, 2, 3])
True
print(3 > 2)
True
print(set([1, 3, 4]) > set([3, 4]))
True
print('xyz' >= 'abc')
True
print(2 == 2)
True
print(set([1, 5, 10]) == set([10, 1, 5]))
True
print(2 != 3)
True
s = set([1, 5, 10])
print(s is s)
True
print(set([1, 5, 10]) is not set([10, 1, 5]))
True
Examples:
Style:
Do not use is/is not when ==/!= are appropriate.
  • x < y : Is x less than y?
  • x <= y : Is x less than or equal to y?
  • x > y : Is x greater than y?
  • x >= y : Is x greater than or equal to y?
  • x == y : Is x equal to y?
  • x != y : Is x not equal to y? (The != operator is meant to evoke the traditional ≠ symbol.)
  • x is y : Is x the same object as y?
  • x is not y : Is x not the same object as y?

The interpretation of the ordering operators, i.e., <, <=, >, >=, depends upon the type of the arguments. In general, you should only compare values of the same type. Comparing values of different type results in a consistent ordering, but not necessarily the same ordering as in another implementation.

Numbers (both integers and floating-point) use their standard order. Booleans use the order than False is less than True. Strings can be thought of as using alphabetic order, although that doesn't capture the whole truth. More accurately, strings use lexicographic order with the ASCII character values. Lists use lexicographic order. Sets use subset. Dictionaries cannot be compared by these operators.

The operator is tests whether the two operands are the same object, whereas == tests whether they have the same value. For mutable types, if x is y, then mutating x also mutates y.

Syntax:
type(x)

Examples:
CodeOutput
print(type(3))
<type 'int'>
print(type(3.2))
<type 'float'>
print(type('Hello'))
<type 'str'>
print(type(True))
<type 'Bool'>
print(type(None))
<type 'NoneType'>
print(type([1, 2, 3]))
<type 'list'>
print(type({1: 2}))
<type 'dict'>
print(type(set([1, 2, 3])))
<type 'set'>
def f():
    return 3
print(type(f))
<type 'function'>
print(type(int))
<type 'type'>

All values have a type, and this returns the type of the given value. The type is itself a value.

Syntax:
isinstance(x, y)

Examples:
CodeOutput
print(isinstance(3, type(3)))
True
print(isinstance(3.1, type(3.1)))
True
print(isinstance('foo', type('foo')))
True
print(isinstance([], type([1, 2, 3])))
True
print(isinstance({1: 2}, type({3: 4})))
True
print(isinstance(set([1, 4]), type(set[])))
True
print(isinstance(3, int))
True
print(isinstance(3.1, float))
True
print(isinstance('foo', str))
True
print(isinstance([], list))
True
print(isinstance({1: 2}, dict))
True
print(isinstance(set([1, 4]), set))
True
def f():
    return 3
def g(x):
    return x
print(isinstance(f, type(g)))
True

If the second argument is a type, for example, as returned by type(), it returns whether the first argument is of that type. If the second argument is a type constructor, it returns whether the first argument is of the type that results from that type constructor.

Syntax:
dir(x)

Example:
CodeOutput
print(dir({}))
['get', 'items', 'keys', 'values']

Returns a list of strings naming the attributes defined on the object x.

Syntax:
hasattr(an_obj, attr_name)

Examples:
CodeOutput
print(hasattr([], 'count'))
True
print(hasattr({1: 2}, 'silly'))
False

Returns whether the given object an_obj has an attribute named by the string attr_name.

Syntax:
callable(an_obj)

Examples:
CodeOutput
print(callable([1, 2, 3]))
False
print(callable(list))
True

Returns whether the given object an_obj is callable, i.e., a built-in function, named function, anonymous function, generator function, or class (which is equivalent to its class constructor).

  • dir with no argument
  • getattr()
  • setattr()
  • object()
  • hash()
  • id()
  • classmethod()
  • staticmethod()
  • issubclass()
  • super()
  • property()
  • memoryview()
  • unicode()

Also, built-in functions and methods aren't considered values and thus don't have a type — thus, type() and isinstance() aren't supported on these.

CodeSkulptor3 implements the following subset of the Python standard library. To use these operations, first import the relevant module with an import statement, such as import math.

Operations:
Example:

This module contains additional mathematical operations. To use these operations, first import the module with import math.

Syntax:
math.isinf(x)

Examples:
CodeOutput
import math

print(math.isinf(8))
False
import math

print(math.isinf(float('+inf')))
True
import math

print(math.isinf(float('-inf')))
True

Returns whether x is infinite.

Syntax:
math.isnan(x)

Examples:
CodeOutput
import math

print(math.isnan(8))
False
import math

print(math.isnan(float('NaN')))
True

Returns whether x is the special floating point Not-a-Number (NaN).

Syntax:
math.ceil(x)

Examples:
CodeOutput
import math

print(math.ceil(8))
8
import math

print(math.ceil(8.1))
9
import math

print(math.ceil(-8.1))
-8
See also:
int() — Round to zero
round() — Rounds to nearest integer
math.trunc() — Rounds to zero
math.floor() — Rounds down

Returns the “ceiling” of x, i.e., the smallest integral value greater than or equal to x. Returns it as an integer.

Syntax:
math.floor(x)

Examples:
CodeOutput
import math

print(math.floor(8))
8
import math

print(math.floor(8.9))
8
import math

print(math.floor(-8.9))
-9
See also:
int() — Round to zero
round() — Rounds to nearest integer
math.trunc() — Rounds to zero
math.ceil() — Rounds up

Returns the “floor” of x, i.e., the largest integral value less than or equal to x. Returns it as an integer.

Syntax:
math.trunc(x)

Examples:
CodeOutput
import math

print(math.trunc(8))
8
import math

print(math.trunc(8.9))
8
import math

print(math.trunc(-8.9))
-8
See also:
int() — Also round to zero
round() — Rounds to nearest integer
math.ceil() — Rounds up
math.floor() — Rounds down

Returns the “truncation” of x, i.e., the integer part of x, ignoring any fractional part. Stated another way, it rounds the number towards zero. On numbers, this is the same behavior as int().

Syntax:
math.fabs(x)

Examples:
CodeOutput
import math

print(math.fabs(3.1))
3.1
import math

print(math.fabs(-3))
3.0
See also:
abs() — Returns an integer when given an integer

Returns the absolute value of the number x as a floating-point value.

Syntax:
math.log(x)
math.log(x, base)
math.log10(x)

Examples:
CodeOutput
import math

print(math.log(math.e ** 3))
3.0
import math

print(math.log(10000, 10))
4.0
import math

print(math.log10(10000))
4.0

math.log() returns the logarithm of x in base base. If the base is omitted, it returns the natural logarithm, i.e., base defaults to math.e.

math.log10() returns the logarithm of x in base 10.

The result is a floating-point.

Syntax:
math.pow(x,y)
math.exp(y)

Examples:
CodeOutput
import math

print(math.pow(2, 3))
8.0
import math

print(math.exp(3))
20.085536923187668
See also:
** — Built-in exponentiation operator
pow() — Built-in exponentiation function

math.pow(x,y) returns x raised to the power y, xy. math.exp(y) returns math.e raised to the power y, ey. The result is a floating-point.

Syntax:
math.factorial(x)

Examples:
CodeOutput
import math

print(math.factorial(0))
1
import math

print(math.factorial(4))
24

Returns the factorial of the non-negative integer x, i.e., 1 * 2 * … * (x - 1) * x. It raises an error on negative and non-integral values.

Syntax:
math.sqrt(x)

Examples:
CodeOutput
import math

print(math.sqrt(16))
4.0
import math

print(math.sqrt(-1))
NaN

Returns the square root of x. The result is a floating-point.

Syntax:
math.e

Example:
CodeOutput
import math

print(math.e)
2.718281828459045

The mathematical constant known as e, the base of the natural logarithm.

Syntax:
math.pi

Example:
CodeOutput
import math

print(math.pi)
3.141592653589793

The mathematical constant known as π, the ratio between the circumference of a circle and its diameter.

Syntax:
math.degrees(x)

Example:
CodeOutput
import math

print(math.degrees(math.pi))
180.0

Returns the radians angle measure x in degrees. The result is a floating-point.

Syntax:
math.radians(x)

Example:
CodeOutput
import math

print(math.radians(180))
3.141592653589793

Returns the degrees angle measure x in radians. The result is a floating-point.

Syntax:
math.hypot(x, y)

Example:
CodeOutput
import math

print(math.hypot(3, 4))
5.0

Returns math.sqrt(x * x + y * y), known as the Euclidean norm. This represents each of the following:

  • the distance from the origin to a point (x, y),
  • the length of a vector between the origin and a point (x, y),
  • the length of the hypotenuse of a right triangle with sides of length x and y.

The result is a floating-point.

Syntax:
math.sin(x)
math.cos(x)
math.tan(x)

Examples:
CodeOutput
import math

print(math.sin(math.pi))
1.22464679915e-16
import math

print(math.cos(math.pi))
-1.0
import math

print(math.tan(math.pi))
-1.22464679915e-16
See also:
math.asin(), math.acos(), math.atan(), math.atan2() — Inverses
math.sinh(), math.cosh(), math.tanh() — Hyperbolic versions

Return the sine, cosine, or tangent, respectively, of x radians. The result is a floating-point.

Syntax:
math.asin(x)
math.acos(x)
math.atan(x)
math.atan2(y, x)

Examples:
CodeOutput
import math

print(math.asin(-1))
-1.57079632679
import math

print(math.acos(-1))
3.14159265359
import math

print(math.atan(-1))
-0.785398163397
import math

print(math.atan2(1, 1))
0.785398163397
import math

print(math.atan2(-1, -1))
-2.35619449019
See also:
math.sin(), math.cos(), math.tan() — Inverses
math.asinh(), math.acosh(), math.atanh() — Hyperbolic versions

Return the arcsine (asin), arccosine (acos), or arctangent (atan), of x. The resulting angle measurement is in radians.

atan2 returns the arctangent of y / x in radians. The point of atan2 is that the signs of the inputs are known, so it can compute the correct quadrant for the angle, as illustrated in the above examples.

Each result is a floating-point.

Syntax:
math.sinh(x)
math.cosh(x)
math.tanh(x)

Examples:
CodeOutput
import math

print(math.sinh(1))
1.17520119364
import math

print(math.cosh(1))
1.54308063482
import math

print(math.tanh(1))
0.761594155956
See also:
math.asinh(), math.acosh(), math.atanh() — Inverses
math.sin(), math.cos(), math.tan() — Non-hyperbolic versions

Return the hyperbolic sine, cosine, or tangent, respectively, of x. The result is a floating-point.

Syntax:
math.asinh(x)
math.acosh(x)
math.atanh(x)

Examples:
CodeOutput
import math

print(math.asinh(-1))
-0.88137358702
import math

print(math.acosh(1))
0.0
import math

print(math.atanh(0))
0.0
See also:
math.asinh(), math.acosh(), math.atanh() — Inverses
math.asin(), math.acos(), math.atan(), math.atan2() — Non-hyperbolic versions

Return the hyperbolic arcsine (asin), arccosine (acos), or arctangent (atan), of x. The result is a floating-point.

  • math.copysign()
  • math.mod()
  • math.frexp()
  • math.fsum()
  • math.ldexp()
  • math.modf()
Operations:
Example:

This module contains functions that involve randomness. To use these operations, first import the module with import random.

Syntax:
random.choice(a_seq)

Example:
CodeOutput
import random

print(random.choice([1, 2, 3, 4, 5, 6]))
# Results in one of the sequence's elements

Returns a random element from the non-empty sequence a_seq. If a_seq is empty, raises an IndexError.

Syntax:
random.randint(start, stop)
random.randrange(stop)
random.randrange(start, stop)
random.randrange(start, stop, step)

Examples:
CodeOutput
import random

print(random.randint(0, 10))
# Possible results are 0, 1, 2, …, 10
import random

print(random.randrange(0, 10))
# Possible results are 0, 1, 2, …, 9
import random

print(random.randrange(0, 10, 2))
# Possible results are 0, 2, 4, 6, 8
See also:
random.choice() — Related to random.randrange()
range() — Related to random.randrange()

random.randint(start, stop) returns a random integer n such that start <= n <= stop.

random.randrange(start, stop, step) is equivalent to random.choice(range(start, stop, step)). In particular, random.randrange(start, stop) returns a random integer n such that start <= n < stop. Each possible n is of the form start + i×step, for some integral i.

For each function, each possible number is equally likely, i.e., the possible numbers are distributed uniformly.

Syntax:
random.random()
random.uniform(x, y)

Examples:
CodeOutput
import random

print(random.random())
# Possible results are 0.0 to 1.0, not including 1.0
import random

lower = 5
upper = 10
range_width = upper - lower
print(random.random() * range_width + lower)
# Possible results are lower to upper, not including upper
import random

print(random.uniform(2, 4))
# Possible results are 2.0 to 4.0
import random

print(random.uniform(4, 2))
# Possible results are 2.0 to 4.0

Returns a random floating-point number. With random.random() the result is in 0 ≤ n < 1, while with random.uniform() the result is in x ≤ n ≤ y (when x ≤ y) or y ≤ n ≤ x (when y ≤ x). Each number is equally likely, i.e., the possible numbers are distributed uniformly.

Syntax:
random.triangular()
random.triangular(low)
random.triangular(low, high)
random.triangular(low, high, mode)

Example:
CodeOutput
import random

print(random.triangular())
# Possible results are 0.0 to 1.0, not including 1.0

Returns a random floating-point number. The result is in low ≤ n ≤ high with a triangular distribution centered on mode. The mode defaults to the midpoint of low and high, which results in a symmetric triangular distribution. Furthermore, low and high default to 0 and 1, respectively.

Syntax:
random.shuffle(a_list)

Examples:
CodeOutput
import random

numbers = range(5)
random.shuffle(numbers)
print(numbers)
[3, 1, 0, 2, 4]   # One possible result
import random

numbers = range(5)
random.shuffle(numbers)
print(numbers)
[2, 4, 3, 1, 0]   # One possible result

Mutates the list a_list to be a random permutation of its elements.

Syntax:
random.seed()
random.seed(x)

Example:
CodeOutput
random.seed()
# no output

Changes the random number generator's seed, which is used to generate future random values. The hashable object x's integer value is used as the seed. If x is omitted or None, the current system time is used.

The current system time is used as the initial seed when the module is first imported.

  • random.shuffle(x, random)
  • random.getstate()
  • random.setstate()
  • random.jumpahead()
  • random.getrandbits()
  • random.sample()
  • random.betavariate()
  • random.expovariate()
  • random.gammavariate()
  • random.gauss()
  • random.lognormvariate()
  • random.normalvariate()
  • random.vonmisesvariate()
  • random.paretovariate()
  • random.weibullvariate()
Operations:
Superclasses:

A default dictionary supports all the standard dictionary operations. The only difference is that when looking up a value, a_defdict[key], if that key has not been added to the dictionary, then some default value can be returned, instead of an raising a KeyError. Providing a default value is particularly useful when the dictionary values will be accumulating information, as this simplifies the initialization for the accumulator.

To use default dictionaries, first import the module with import collections.

Syntax:
collections.defaultdict()
collections.defaultdict(default_fun)
collections.defaultdict(default_fun, an_iter)

Examples:
CodeOutput
import collections

d = collections.defaultdict()
print(d[1])
Line 4: KeyError: 1
import collections

d = collections.defaultdict(None)
print(d[1])
Line 4: KeyError: 1
import collections

def factory():
    '''Returns a default value.'''
    return 'Hi!'

d = collections.defaultdict(factory)
print(d[1])
Hi!
import collections

def factory():
    '''Returns a default value.'''
    return 'Hi!'

d = collections.defaultdict(factory, [(0, 'Hello!')])
print(d[0])
print(d[1])
Hello!
Hi!
import collections

def add_to_dict(d, key, value):
    '''
    Adds value to a list associated with that
    key in the defaultdict d.
    '''
    d[key].append(value)

d = collections.defaultdict(lambda : [])

add_to_dict(d, 1, 'a')
add_to_dict(d, 1, 'b')
print(d[1])
['a', 'b']
See also:
Dictionaries — No default values
Counters — Specialized to integer values

The default_fun argument is a zero-argument function which returns the default value for any previously undefined key during a lookup. This is known as the default factory. If the factory is the special value None, which is the default value if no argument is given, then keys will not have a default value during lookup, and thus that default dictionary will behave like a standard dictionary.

The optional iterable or iterator an_iter is treated the same as with dict() to initialize the dictionary contents.

Syntax:
a_defdict.default_factory

Example:
CodeOutput
import collections

d = collections.defaultdict(None)
print(d.default_factory)
None

The default factory function for a default dictionary can be accessed via this attribute.

  • Assigning to a_defdict.default_factory.
  • a_defdict.__missing__()
Operations:
Superclasses:

A Counter is a mapping from keys to integers. These integers are traditionally used as counts, but negative integers are also allowed. When looking up a key that has not been previously added to the counter, its value will be zero.

To use these Counters, first import the module with import collections.

Syntax:
collections.Counter()
collections.Counter(an_iter)

Examples:
CodeOutput
import collections

print(collections.Counter({'a': 3, 'c': -1}))
Counter({'a': 3, 'c': -1})
import collections

c = collections.Counter()
c['a'] += 1
print(c['a'])
print(c['b'])
1
0
import collections

c = collections.Counter({'a': 3, 'c': -1})
c['a'] += 1
print(c['a'])
print(c['b'])
4
0
See also:
Dictionaries — Counters support almost all dictionary operations.
Default dictionaries — Counters are specialized to integral values.

Returns a new Counter, possibly initialized with counts provided in the iterable an_iter.

Syntax:
a_counter.elements()

Example:
CodeOutput
import collections

c = collections.Counter({'a': 3, 'c': 8})
i = c.elements()
print(i.next())
print(i.next())
('a', 3)
('c', 8)

Creates an iterator whose elements are the key/value pairs of the counter a_counter. The iterator's elements will be in an arbitrary implementation-specific order.

Syntax:
a_counter.most_common()
a_counter.most_common(n)

Examples:
CodeOutput
import collections

print(collections.Counter({'a': 3, 'b': 5, 'c': 1, 'd': 3}).most_common())
[('b', 5), ('a', 3), ('d', 3), ('c', 1)]
import collections

print(collections.Counter({'a': 3, 'b': 5, 'c': 1, 'd': 3}).most_common(2))
[('b', 5), ('a', 3)]

Returns a list of pairs of the counter a_counter's n most common keys and corresponding values, listed in descending value order. Keys with the same value are listed in arbitrary order. If n is not specified, then all key-value pairs are listed.

Syntax:
a_counter.subtract(an_iter)

Example:
CodeOutput
import collections

c = collections.Counter({'a': 1, 'b': 2})
c.subtract({'a': 4, 'c': 3})
print(c)
Counter({'a': -3, 'b': 2, 'c': -3})

Mutates counter a_counter by subtracting each key's respective value in an_iter from its value in a_counter.

Syntax:
a_counter.update(an_iter)

Example:
CodeOutput
import collections

c = collections.Counter({'a': 1, 'b': 2})
c.update({'a': 4, 'c': 3})
print(c)
Counter({'a': 5, 'b': 2, 'c': 3})

Mutates counter a_counter by adding each key's respective value in an_iter from its value in a_counter.

Operations:
Documentation:

This module allows use of regular expressions, also known as regexps. To use these operations, first import the module with import re.

Most of the Python regular expression syntax is supported.

Syntax:
re.findall(pattern, string)
re.findall(pattern, string, flags = val)

Examples:
CodeOutput
import re

print(re.findall(r'ZZZ', 'a quick brown fox'))
[]
import re

print(re.findall(r'[a-z]*o[a-z]*', 'a quick brown fox'))
['brown', 'fox']
import re

print(re.findall('[a-z]*a[a-z]*', 'A stitch in time saves nine.', re.IGNORECASE))
['A', 'saves']

Returns a list of all the matches of the regular expression pattern in the given text string.

Syntax:
re.search(pattern, string)
re.search(pattern, string, flags = val)

Examples:
CodeOutput
import re

print(re.search(r'ZZZ', 'a quick brown fox'))
None
import re

if re.search(r'ZZZ', 'a quick brown fox'):
    print('Found pattern.')
else:
    print('Did not find pattern.')
Did not find pattern.
import re

m = re.search(r'[a-z]*o[a-z]*', 'a quick brown fox')
print(m.group(0))
brown
import re

m = re.search('[a-z]*a[a-z]*', 'A stitch in time saves nine.', re.IGNORECASE)
print(m.group(0))
A

Returns the first match, if any, of the regular expression pattern in the given text string.

Syntax:
re.match(pattern, string)
re.match(pattern, string, flags = val)

Examples:
CodeOutput
import re

print(re.match(r'ZZZ', 'a quick brown fox'))
None
import re

if re.match(r'ZZZ', 'a quick brown fox'):
    print('Found pattern.')
else:
    print('Did not find pattern.')
Did not find pattern.
import re

print(re.match(r'[a-z]*o[a-z]*', 'a quick brown fox'))
None
import re

m = re.match('[a-z]*a[a-z]*', 'A stitch in time saves nine.', re.IGNORECASE)
print(m.group(0))
A

Returns the match, if any, of the regular expression pattern at the beginning of the given text string.

Syntax:
re.split(pattern, string)
re.split(pattern, string, maxsplit = val)
re.split(pattern, string, maxsplit = val, flags = val)

Examples:
CodeOutput
import re

print(re.split(r's+', 'a quick brown fox'))
['a', 'quick', 'brown', 'fox']
import re

print(re.split(r's+', 'a quick brown fox', 2))
['a', 'quick', 'brown fox']
import re

print(re.split(r'(s+)', 'a quick brown fox'))
['a', ' ', 'quick', ' ', 'brown', ' ', 'fox']
import re

print(re.split('a', 'A stitch in time saves nine.', 0, re.IGNORECASE))
['', ' stitch in time s', 'ves nine.']

Splits the given text string into a list of strings, using the pattern regular expression as separators. If the regular expression is surrounded by parentheses, then the instances of the separators are included in the list of strings, otherwise they are not.

If maxsplit is positive, then it splits the text at the first maxsplit occurrences of the pattern. If flags is positive, then the pattern is modified by the flags.

Syntax:
re.I
re.IGNORECASE

Flag to indicate that regular expression pattern matching should be case-insensitive. By default, matching is case sensitive.

Syntax:
match_obj.group(a_num)
match_obj.groups(a_num)

Documentation:
  • re.compile()
  • re.finditer()
  • re.sub()
  • re.subn()
  • re.escape()
  • re.purge()
  • re.DEBUG
  • re.L
  • re.LOCALE
  • re.M
  • re.MULTILINE
  • re.S
  • re.DOTALL
  • re.U
  • re.UNICODE
  • re.X
  • re.VERBOSE
  • match_obj.expand()
  • match_obj.groupdict()
  • match_obj.start()
  • match_obj.end()
  • match_obj.span()
  • match_obj.pos
  • match_obj.endpos
  • match_obj.lastindex
  • match_obj.lastgroup
  • match_obj.re
  • match_obj.string
Operation:

This module includes operations that measure the passage of time. To use these operations, first import the module with import time.

Syntax:
time.time()

Examples:
CodeOutput
import time

print(time.time())
1349712380.59    # One possible output.
import time

time1 = time.time()
…      # The code being timed
time2 = time.time()
print('Time elapsed:', time2 - time1)
Time elapsed: 2.64113    # One possible output.

Returns the current time as the number of seconds since some constant system-defined time.

A common usage is to measure the time to run an operation, as in the last example above.

  • time.accept2dyear
  • time.altzone
  • time.asctime()
  • time.clock()
  • time.ctime()
  • time.daylight
  • time.gmtime()
  • time.localtime()
  • time.mktime()
  • time.sleep()
  • time.strftime()
  • time.strptime()
  • time.struct_time
  • time.timezone
  • time.tzname
  • time.tzset()
Operation:
See also:
File Objects — Operations on opened files
codeskulptor.file2url — Abbreviating standard URLs

This module contains functions for obtaining input data from the web. Currently, CodeSkulptor's implementation of this module supports input only, not output, and only from a a CodeSkulptor-affiliated data storage site. To use these operations, first import the module with import urllib.request.

File objects represent open files. A file object keeps track of the current position in the file. Each read operation gets data starting at this position and advances the position to the end of the returned data. CodeSkulptor only supports obtaining an open file via urllib.request.urlopen().

Syntax:
urllib.request.urlopen(url)

Example:
CodeOutput
import urllib.request
import codeskulptor

a_file = urllib.request.urlopen(codeskulptor.file2url('assets_sample_text.txt'))
print(a_file.read())
This is line one.
This is line two.
This is line three.

Returns a read-only file object of the data found at the given URL. Causes no error if there is no such URL.

Currently, the only URLs that are supported are those files provided by the CodeSkulptor authors.

  • urllib.request.urlopen() with multiple arguments
  • urllib.request.install_opener()
  • urllib.request.build_opener()

CodeSkulptor3 implements three custom modules for graphics in the browser, each with an easy-to-learn interface. The SimpleGUI module is for building interactive programs and drawing. The SimpleMap module is for drawing features on maps. The SimplePlot module is for plotting numeric data. To use these operations, first import the appropriate module with import simplegui, import simplemap, or import simpleplot.

Operations:
Superclass:
Example:

A frame is a window, which is a container for the controls, status information, and canvas. A program can create only one frame.

Syntax:
simplegui.create_frame(title, canvas_width, canvas_height)
simplegui.create_frame(title, canvas_width, canvas_height, control_width)

Examples:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
# Opens frame
import simplegui

frame = simplegui.create_frame('Testing', 200, 200, 300)
# Opens frame

Creates a new frame for interactive programs. The frame's window has the given title, a string. The frame consists of two parts: a control panel on the left and a canvas on the right. The control panel's width in pixels can be specified by the number control_width. The canvas width in pixels is the number canvas_width. The height in pixels of both the control panel and canvas is the number canvas_height.

Syntax:
frame.set_canvas_background(color)

Example:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_canvas_background('Red')
frame.start()
# Opens frame with a red background
See also:
Colors — Supported colors

Changes the background color of the frame's canvas, which defaults to black.

Syntax:
frame.start()

Example:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
frame.start()
# Opens frame

Starts all frame event handlers — drawing and controls.

Syntax:
frame.get_canvas_textwidth(text, size)
frame.get_canvas_textwidth(text, size, face)

Examples:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
print frame.get_canvas_textwidth('hello', 12)
23
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
print frame.get_canvas_textwidth('hello', 12, 'sans-serif')
27

Given a text string, a font size, and a font face, this returns the width of the text in pixels. It does not draw the text. This is useful in computing the position to draw text when you want it centered or right justified in some region.

The supported font faces are the default 'serif', 'sans-serif', and 'monospace'.

Operations:
Superclass:

Control objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-down in the order of creation. Status information is at the bottom of the control panel.

Syntax:
frame.add_label(text)
frame.add_label(text, width)

Example:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
label1 = frame.add_label('My first label')
label2 = frame.add_label('My second label', 200)
label3 = frame.add_label('My third label', 20)
# Opens frame with three labels
See also:
control.get_text() — Gets the current label text
control.set_text() — Sets the current label text

Adds a text label to the control panel. The width of the label defaults to fit the width of the given text, but can be specified in pixels. If the provided width is less than that of the text, the text overflows the label.

Syntax:
frame.add_button(text, button_handler)
frame.add_button(text, button_handler, width)

Example:
CodeOutput
import simplegui

def button_handler():
    …

frame = simplegui.create_frame('Testing', 100, 100)
button1 = frame.add_button('Label 1', button_handler)
button2 = frame.add_button('Label 2', button_handler, 50)
# Opens frame with two buttons
Example:
See also:
control.get_text() — Gets the current label text
control.set_text() — Sets the current label text

Adds a button to the frame's control panel with the given text label. The width of the button defaults to fit the given text, but can be specified in pixels. If the provided width is less than that of the text, the text overflows the button.

The handler should be defined with no parameters, as in the above example.

Syntax:
frame.add_input(text, input_handler, width)

Example:
CodeOutput
import simplegui

def input_handler(text_input):
    …

frame = simplegui.create_frame('Testing', 100, 100)
inp = frame.add_input('My label', input_handler, 50)
# Opens frame with one input box
Example:
See also:
control.get_text() — Gets the current input text
control.set_text() — Sets the current input text, e.g., to specify a default value

Adds a text input field to the control panel with the given text label. The input field has the given width in pixels.

The handler should be defined with one parameter, as in the above example. This parameter will receive a string of the text input when the user presses the Enter key.

Syntax:
control.get_text()

Examples:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
label = frame.add_label('Label')
label.set_text('New label')
print(label.get_text())
New label
import simplegui

def button_handler():
    …

frame = simplegui.create_frame('Testing', 100, 100)
button = frame.add_button('Press this button', button_handler)
print(button.get_text())
Press this button
import simplegui

def input_handler(text_input):
    …

frame = simplegui.create_frame('Testing', 100, 100)
inp = frame.add_input('Label', input_handler, 50)
print(inp.get_text())
See also:
control.set_text() — Sets the text

Returns the text in a label, the text label of a button, or the text in the input field of a text input, respectively. For an input field, this is useful to look at the contents of the input field before the user presses the Enter key.

Syntax:
control.set_text(text)

Examples:
CodeOutput
import simplegui

frame = simplegui.create_frame('Testing', 100, 100)
label = frame.add_label('Label')
label.set_text('New label')
# Opens frame with a text string
import simplegui

def button_handler():
    …

frame = simplegui.create_frame('Testing', 100, 100)
button = frame.add_button('Label', button_handler)
button.set_text('New label')
# Opens frame with one button
import simplegui

def input_handler(text_input):
    …

frame = simplegui.create_frame('Testing', 100, 100)
inp = frame.add_input('Label', input_handler, 50)
inp.set_text('Default contents')
# Opens frame with one input box
See also:
control.get_text() — Gets the text

Changes the text in a label, the text label of a button, or the text in the input field of a text input, respectively. For a button, it also resizes the button if the button wasn't created with a particular width. For an input field, this is useful to provide a default input for the input field.

Syntax:
frame.set_keydown_handler(key_handler)
frame.set_keyup_handler(key_handler)

Example:
CodeOutput
import simplegui

def key_handler(key):
    …

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_keydown_handler(key_handler)
frame.start()
# Opens frame with active keydown handler
Example:

These add keyboard event handlers waiting for keydown, and keyup events, respectively. When any key is pressed, the keydown handler is called once. When any key is released, the keyup handler is called once.

The handler for each should be defined with one parameter, as in the above example. This parameter will receive an integer representing a keyboard character.

Syntax:
frame.set_mouseclick_handler(mouse_handler)
frame.set_mousedrag_handler(mouse_handler)

Example:
CodeOutput
import simplegui

def mouse_handler(position):
    …

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_mouseclick_handler(mouse_handler)
frame.start()
# Opens frame with active mouseclick handler
Examples:

These add keyboard event handlers waiting for mouseclick and mousedrag events, respectively. When a mouse button is clicked, i.e., pressed and released, the mouseclick handler is called once. When a mouse is dragged while the mouse button is being pressed, the mousedrag handler is called for each new mouse position.

The handler for each should be defined with one parameter, as in the above example. This parameter will receive a pair of screen coordinates, i.e., a tuple of two non-negative integers.

Operations:
Superclass:
Examples:

The canvas is where you can draw text and shapes.

Syntax:
frame.set_draw_handler(draw_handler)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    …

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame with active draw handler

Adds an event handler that is responsible for all drawing.

The handler should be defined with one parameter, as in the above example. This parameter will receive a canvas object.

Syntax:
canvas.draw_text(text, point, font_size, font_color)
canvas.draw_text(text, point, font_size, font_color, font_face)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    canvas.draw_text('A', (20, 20), 12, 'Red')
    canvas.draw_text('B', [30, 50], 20, 'Blue')
    canvas.draw_text('C', (80, 50), 12, 'Gray', 'serif')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws three letters
See also:
Colors — Supported colors

Writes the given text string in the given font size, color, and font face. The point is a 2-element tuple or list of screen coordinates representing the lower-left-hand corner of where to write the text.

The supported font faces are 'serif' (the default), 'sans-serif', and 'monospace'.

In order to position the text where you want, you may want to determine the text's width.

Syntax:
canvas.draw_line(point1, point2, line_width, line_color)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    canvas.draw_line((10, 20), (30, 40), 12, 'Red')
    canvas.draw_line([10, 20], [80, 70], 20, 'Blue')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws two lines
Example:
See also:
Colors — Supported colors

Draws a line segment between the two points, each of which is a 2-element tuple or list of screen coordinates. The line's width is given in pixels and must be positive.

Syntax:
canvas.draw_polyline(point_list, line_width, line_color)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    canvas.draw_polyline([(10, 20), (30, 20), (90, 70)], 12, 'Red')
    canvas.draw_polyline([[40, 20], [80, 40], [30, 90]], 20, 'Blue')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws two polylines
See also:
Colors — Supported colors

Draws a sequence of line segments between each adjacent pair of points in the non-empty list. It is an error for the list of points to be empty. Each point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels and must be positive.

Syntax:
canvas.draw_polygon(point_list, line_width, line_color)
canvas.draw_polygon(point_list, line_width, line_color, fill_color = color)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    canvas.draw_polygon([(10, 20), (20, 30), (30, 10)], 12, 'Green')
    canvas.draw_polygon([[30, 20], [40, 40], [50, 20], [10, 10]], 12, 'Red')
    canvas.draw_polygon([(50, 70), (80, 40), (30, 90)], 5, 'Blue', 'White')
    canvas.draw_polygon([[90, 70], [80, 40], [70, 90], [70, 70]], 12, 'Yellow', 'Orange')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws four polygons
See also:
Colors — Supported colors

Draws a sequence of line segments between each adjacent pair of points in the non-empty list, plus a line segment between the first and last points. It is an error for the list of points to be empty. Each point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels, and must be positive. The fill color defaults to None. If the fill color is specified, then the interior of the polygon is colored.

Syntax:
canvas.draw_circle(center_point, radius, line_width, line_color)
canvas.draw_circle(center_point, radius, line_width, line_color, fill_color = color)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    canvas.draw_circle((10, 10), 20, 12, 'Green')
    canvas.draw_circle([20, 30], 30, 12, 'Red')
    canvas.draw_circle((50, 50), 20, 5, 'Blue', 'White')
    canvas.draw_circle([70, 80], 30, 10, 'Yellow', 'Orange')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws four circles
See also:
Colors — Supported colors
draw_arc — Draws an arc of a circle.

Draws a circle at the given center point having the given radius. The point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels and must be positive. The fill color defaults to None. If the fill color is specified, then the interior of the circle is colored.

Syntax:
canvas.draw_arc(center_point, radius, start_angle, end_angle, line_width, line_color)
canvas.draw_arc(center_point, radius, start_angle, end_angle, line_width, line_color, fill_color = color)

Example:
CodeOutput
import simplegui
import math

def draw_handler(canvas):
    canvas.draw_arc((10, 10), 20, 0, math.pi, 12, 'Green')
    canvas.draw_arc([20, 30], 30, math.pi, 2*math.pi, 12, 'Red')
    canvas.draw_arc((50, 50), 20, 0.5*math.pi, 1.5*math.pi, 5, 'Blue', 'White')
    canvas.draw_arc([70, 80], 30, 0, 0.5*math.pi, 10, 'Yellow', 'Orange')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws four arcs
See also:
Colors — Supported colors
draw_circle — Draws a full circle.

Draws an arc at the given center point having the given radius. The point is a 2-element tuple or list of screen coordinates. The starting and ending angles indicate which part of a circle should be drawn. Angles are given in radians, clockwise starting with a zero angle at the 3 o'clock position. The line's width is given in pixels and must be positive. The fill color defaults to None. If the fill color is specified, then the interior of the circle is colored.

Syntax:
canvas.draw_point(point, color)

Example:
CodeOutput
import simplegui

def draw_handler(canvas):
    canvas.draw_point((10, 10), 'Green')
    canvas.draw_point([20, 30], 'Red')

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws two points
See also:
Colors — Supported colors

Draws a 1×1 rectangle at the given point in the given color. The point is a 2-element tuple or list of screen coordinates.

Syntax:
canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest)
canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest, rotation)

Examples:
CodeOutput
import simplegui
import codeskulptor

def draw_handler(canvas):
    canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100))

image = simplegui.load_image(codeskulptor.file2url('assets_gutenberg.jpg'))

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws a scaled map
import simplegui
import codeskulptor

def draw_handler(canvas):
    canvas.draw_image(image, (1521 // 2, 1818 // 2), (1521, 1818), (40, 70), (100, 100), 2)

image = simplegui.load_image(codeskulptor.file2url('assets_gutenberg.jpg'))

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws a strangely rotated scaled map
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
simplegui.load_image — Loading image file

Draw an image that was previously loaded. center_source is a pair of coordinates giving the position of the center of the image, while center_dest is a pair of screen coordinates specifying where the center of the image should be drawn on the canvas. width_height_source is a pair of integers giving the size of the original image, while width_height_dest is a pair of integers giving the size of how the images should be drawn. The image can be rotated clockwise by rotation radians.

You can draw the whole image file or just part of it. The source information (center_source and width_height_source) specifies which pixels to display. If it attempts to use any pixels outside of the actual file size, then no image will be drawn.

Specifying a different width or height in the destination than in the source will rescale the image.

Operations:
Superclass:
Example:

A timer calls an event handler repeatedly at a specified interval.

A program can have an arbitrary number of timers running simultaneously. However, having many timers running will slow CodeSkulptor.

Syntax:
simplegui.create_timer(interval, timer_handler)

Example:
CodeOutput
import simplegui

def timer_handler():
    …

timer = simplegui.create_timer(500, timer_handler)
timer.start()
# starts a timer

Creates a timer. Once started, it will repeatedly call the given event handler at the specified interval, which is given in milliseconds.

The handler should be defined with no arguments, as in the above example.

Syntax:
timer.start()

Example:
CodeOutput
import simplegui

def timer_handler():
    …

timer = simplegui.create_timer(500, timer_handler)
timer.start()
# starts a timer

Starts or restarts the timer.

Syntax:
timer.stop()

Example:
CodeOutput
import simplegui

def timer_handler():
    timer.stop()

timer = simplegui.create_timer(500, timer_handler)
timer.start()
# starts a timer and stops it on its first tick

Stops the timer. It can be restarted.

Syntax:
timer.is_running()

Example:
CodeOutput
import simplegui

def timer_handler():
    pass

timer = simplegui.create_timer(100, timer_handler)
print(timer.is_running())
timer.start()
print(timer.is_running())
timer.stop()
print(timer.is_running())
False
True
False

Returns whether the timer is running, i.e., it has been started, but not stopped.

Operations:
Superclass:
Example:

An image must be loaded before it can be drawn.

Syntax:
simplegui.load_image(URL)

Example:
CodeOutput
import simplegui
import codeskulptor

def draw_handler(canvas):
    canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100))

image = simplegui.load_image(codeskulptor.file2url('assets_gutenberg.jpg'))

frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Opens frame and draws a scaled map
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
canvas.draw_image — Drawing image file

Loads an image from the specified URL. The image can be in any format supported by the browser. No error is raised if the file isn't found or is of an unsupported format.

Syntax:
image.get_width()

Returns the width of the image in pixels. While the image is still loading, it returns zero.

Syntax:
image.get_height()

Returns the height of the image in pixels. While the image is still loading, it returns zero.

Operations:
Superclass:

A sound must be loaded before it can be played. To restart playing a sound from the beginning, it must first be rewound. Separate sounds are played in separate audio channels and may overlap. The number of sounds that can be played simultaneously is system-dependent.

Syntax:
simplegui.load_sound(URL)

Example:
CodeOutput
import simplegui
import codeskulptor

sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg'))
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
sound.play() — How to play the sound

Loads a sound from the specified URL. Supports whatever audio formats that your browser supports. No error is raised if the file isn't found or is of an unsupported format.

Syntax:
sound.play()

Example:
CodeOutput
import simplegui
import codeskulptor

sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg'))
sound.play()
# plays a sound
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
simplegui.load_sound() — How to load a sound

Starts playing a sound, or restarts playing it at the point it was paused.

Syntax:
sound.pause()

Example:
CodeOutput
import simplegui
import codeskulptor

sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg'))
sound.play()
sound.pause()
# starts to play a sound, then immediately pauses
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
simplegui.load_sound() — How to load a sound
sound.play() — How to play the sound

Stops the playing of the sound. Playing can be restarted at the stopped point with sound.play().

Syntax:
sound.rewind()

Example:
CodeOutput
import simplegui
import codeskulptor

sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg'))
sound.play()
sound.rewind()
sound.play()
# starts to play a sound, rewinds it, then plays it again from the beginning
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
simplegui.load_sound() — How to load a sound
sound.play() — How to play the sound

Stops the playing of the sound, and makes it so the next sound.play() will start playing the sound at the beginning.

Syntax:
sound.set_volume(volume)

Example:
CodeOutput
import simplegui
import codeskulptor

sound = simplegui.load_sound(codeskulptor.file2url('assets_Epoq-Lepidoptera.ogg'))
sound.set_volume(0.7)
sound.play()
See also:
codeskulptor.file2url — Converting CodeSkulptor filename to URL
simplegui.load_sound() — How to load a sound
sound.play() — How to play the sound

Changes the volume for the sound to be the given level on a 0 (silent)–1.0 (maximum) scale. Default is 1.

The following color names are considered the most standard.

'Aqua'      
'Black'      
'Blue'      
'Fuchsia'      
'Gray'      
'Green'      
'Lime'      
'Maroon'      
'Navy'      
'Olive'      
'Orange'      
'Purple'      
'Red'      
'Silver'      
'Teal'      
'White'      
'Yellow'      

More generally, you may use any HTML color name. Furthermore, custom colors and transparencies can be specified in a any CSS color format, including hexadecimal, RGB, RGBA, HSL, and HSLA.

Syntax:
simplegui.KEY_MAP[character]

Example:
CodeOutput
import simplegui

print(simplegui.KEY_MAP['left'])
37

The keyboard event handlers receive the relevant key as an integer. Because different browsers can give different values for the same keystrokes, SimpleGUI provides a way to get the appropriate key integer for a given meaning.

The acceptable strings for character are the letters 'a''z' and 'A''Z', the digits '0''9', 'space', 'left', 'right', 'up', and 'down'. Note that other keyboard symbols are not defined in simplegui.KEY_MAP.

Operations:
Superclass:

The SimpleMap module provides an interface for drawing and annotating maps. The underlying maps are provided by Google Maps. Points on the map are referred to by a pair of numbers representing latitude and longitude.

The module uses three types of objects: maps, markers, and lines.

Syntax:
simplemap.create_map(title, coordinates, map_width, map_height)
simplemap.create_map(title, coordinates, map_width, map_height, control_width)

Example:
CodeOutput
import simplemap

simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
# Creates a map.

Creates a map in a new window titled by the string title and with the given width and height in pixels. The map contents are centered on the given coordinates in latitude and longitude.

If a control_width is given, it also creates an control panel. By default, no area is created, and such button controls are not allowed.

Syntax:
a_map.add_marker(description, id, icon_url, coordinates, handler)

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
# Creates a map with one marker.

Draws a marker on the map, adds a corresponding marker object to the map object, and returns the marker object. The marker is represented graphically by the image found at the URL string icon_url. The marker is placed at the latitude and longitude specified by the pair of numbers coordinates. The marker has a description string which appears when you hover the mouse on the marker. The marker also has an id data string. When the image is clicked on, the event handler function click_handler will be called.

The handler should be defined with one parameter, as in the above example. This parameter will receive the marker object whose image was clicked on.

Syntax:
a_map.draw_line(start_marker, stop_marker)

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

rice.draw_line(wiess_college, duncan_hall)
# Draws a line between two map markers

Draws a black path between the two given markers on the map. The path follows the available streets. Adds a corresponding line object to the map object, and returns the line object.

Syntax:
a_map.get_markers()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

for marker in rice.get_markers():
    print(marker.get_description())
Wiess College
Duncan Hall

Returns a set of all marker objects represented on the map.

Syntax:
map.get_lines()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

rice.draw_line(wiess_college, duncan_hall)

for line in rice.get_lines():
    print(line.get_start().get_description())
    print(line.get_stop().get_description())
Wiess College
Duncan Hall

Returns a set of all line objects represented on the map.

Syntax:
a_map.clear_markers()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

rice.draw_line(wiess_college, duncan_hall)

rice.clear_markers()

print(rice.get_markers())
set([])
See also:
map.clear() — Removes all markers and lines
marker.remove() — Removes one marker

Erases all markers from the drawn map. Does not remove any lines between those markers. Removes all marker objects from the map object.

Syntax:
a_map.clear_lines()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

rice.draw_line(wiess_college, duncan_hall)

rice.clear_lines()

print(rice.get_lines())
set([])
See also:
map.clear() — Removes all markers and lines
a_line.remove() — Removes one line

Erases all paths from the drawn map. Does not remove any markers. Removes all line objects from the map object.

Syntax:
a_map.clear()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

rice.draw_line(wiess_college, duncan_hall)

rice.clear()

print(rice.get_markers())
print(rice.get_lines())
set([])
set([])
See also:
map.clear_markers() — Removes all markers
map.clear_lines() — Removes all lines

Erases all markers and line segments from the drawn map. Removes all marker objects and line objects from the map object.

Syntax:
a_map.add_button(text, handler)
a_map.add_button(text, handler, width)

Example:
CodeOutput
import simplemap

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500, 150)

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

def delete_wiess ():
    rice.clear_markers()

rice.add_button('Delete Wiess Marker', delete_wiess)
# Creates map with button that will delete a marker

Adds a button in the map's control panel with the given text label. The width of the button defaults to the width of the given text, but can be specified in pixels. If the provided width is less than that of the text, the text overflows the button.

Syntax:
a_map.add_break()

Example:
CodeOutput
import simplemap

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500, 150)

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

def delete_wiess ():
    rice.clear_markers()

rice.add_button('Delete Wiess Marker', delete_wiess)
rice.add_break()
rice.add_button('Delete Wiess Marker', delete_wiess)
# Creates map with two buttons that will delete a marker

Adds a line break to the map's control panel. Useful to separate buttons.

Operations:
Superclass:

A marker object corresponds to a drawn marker icon image on the map. Its location is determined by a pair of latitude and longitude coordinates.

Syntax:
a_marker.get_description

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

print(wiess_college.get_description())
Wiess College

Returns the description string of the marker.

Syntax:
a_marker.get_id()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

print wiess_college.get_id()
W

Returns the ID string of the marker.

Syntax:
a_marker.get_coordinates()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

print wiess_college.get_coordinates()
(29.714967, -95.400694)

Returns the latitude and longitude coordinates of the marker as a pair of numbers.

Syntax:
a_marker.get_icon()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

print(wiess_college.get_icon())
http://labs.google.com/ridefinder/images/mm_20_green.png

Returns the icon URL of the marker.

Syntax:
a_marker.set_icon(URL)

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

wiess_college.set_icon(red_icon)
print(wiess_college.get_icon())
http://labs.google.com/ridefinder/images/mm_20_red.png

Changes the icon of the marker to be the image at the given URL.

Syntax:
a_marker.remove()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)

wiess_college.remove()

print(rice.get_markers())
set([])
See also:
map.clear_markers() — Removes all markers
map.clear() — Removes all markers and lines

Erases the marker from the drawn map. Does not remove any lines using the marker. Removes the marker object from the map object.

Operations:
Superclass:

A line object corresponds to a drawn path between two markers on the map. The path follows the available streets on the map. The path color defaults to black.

Syntax:
a_line.get_start()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

line = rice.draw_line(wiess_college, duncan_hall)

print(line.get_start().get_description())
Wiess College

Returns the starting, i.e., first, marker of a line.

Syntax:
a_line.get_stop()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

line = rice.draw_line(wiess_college, duncan_hall)

print(line.get_stop().get_description())
Duncan Hall

Returns the stopping, i.e., second, marker of a line.

Syntax:
a_line.set_color(color)

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

line = rice.draw_line(wiess_college, duncan_hall)

line.set_color('Yellow')
# Draws a yellow line on a map
See also:
Colors — Supported colors

Changes the color of the path, which defaults to black, between the two endpoint markers of the line.

Syntax:
a_line.remove()

Example:
CodeOutput
import simplemap

def click_handler(a_marker):
    print('Clicked on marker', a_marker.get_description())

green_icon = 'http://labs.google.com/ridefinder/images/mm_20_green.png'
red_icon = 'http://labs.google.com/ridefinder/images/mm_20_red.png'

rice = simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
wiess_college = rice.add_marker('Wiess College', 'W', green_icon, (29.714967, -95.400694), click_handler)
duncan_hall = rice.add_marker('Duncan Hall', 'D', red_icon, (29.719887, -95.398617), click_handler)

line = rice.draw_line(wiess_college, duncan_hall)

line.remove()

print(rice.get_lines())
set([])
See also:
map.clear_lines() — Removes all lines
map.clear() — Removes all markers and lines

Erases the line from the drawn map. Does not remove the endpoint markers of the line. Removes the line object from the map object.

Operations:

SimplePlot provides functions for plotting numeric data — both the x- and y-coordinate values should be numbers. To use its operations, first import the module with import simpleplot.

Syntax:
simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points)
simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points, legends)

Example:
CodeOutput
import simpleplot

dataset1 = {3: 5, 8: 2, 1: 3}
dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)]
simpleplot.plot_lines('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], True, ['dataset1', 'dataset2'])
# pops up a line plot

Displays a plot in a new window named framename with the width and height given in pixels. The x-axis is labeled with the string xlabel. The y-axis is labeled with the string ylabel.

The data to display is given in datasets, which is a sequence of data sets. Each data set is connected with a line through each data point. Each data set can be given in either of two representations.

  • A data set can be a sequence of 2-element sequences, where a 2-element sequence represents an x,y-pair. This allows for multiple points to have the same x value. Points are displayed in the given order.
  • A data set can also be a dictionary mapping each x value to a corresponding y value. Points are displayed in order of x value.

The optional boolean points indicates that the individual points should be indicated. It defaults to False.

The optional legends is a sequence of strings that label the data sets and will be displayed in a legend. If omitted, there will be no legend. The length of this sequence should be the same as the length of datasets.

Syntax:
simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets, legends)

Example:
CodeOutput
import simpleplot

dataset1 = {3: 5, 8: 2, 1: 3}
dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)]
simpleplot.plot_bars('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2'])
# pops up a bar plot

Displays a plot in a new window named framename with the width and height given in pixels. The x-axis is labeled with the string xlabel. The y-axis is labeled with the string ylabel.

The data to display is given in datasets, which is a sequence of data sets. Each data point is represented by a vertical bar, and corresponding data points of each data set are grouped together. Each data set can be given in either of two representations.

  • A data set can be a sequence of 2-element sequences, where a 2-element sequence represents an x,y-pair. This allows for multiple points to have the same x value. Points are displayed in the given order.
  • A data set can also be a dictionary mapping each x value to a corresponding y value. Points are displayed in order of x value.

The optional legends is a sequence of strings that label the data sets and will be displayed in a legend. If omitted, there will be no legend. The length of this sequence should be the same as the length of datasets.

Syntax:
simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets)
simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets, legends)

Example:
CodeOutput
import simpleplot

dataset1 = {3: 5, 8: 2, 1: 3}
dataset2 = [(1, 2), (4, 7), (1, 5), (2, 5), (4, 3), (7, 6)]
simpleplot.plot_scatter('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2'])
# pops up a scatter plot

Displays a plot in a new window named framename with the width and height given in pixels. The x-axis is labeled with the string xlabel. The y-axis is labeled with the string ylabel.

The data to display is given in datasets, which is a sequence of data sets. Each data point is represented by a colored dot, and corresponding data points of each data set are the same color. Each data set can be given in either of two representations.

  • A data set can be a sequence of 2-element sequences, where a 2-element sequence represents an x,y-pair. This allows for multiple points to have the same x value. Points are displayed in the given order.
  • A data set can also be a dictionary mapping each x value to a corresponding y value.

The optional legends is a sequence of strings that label the data sets and will be displayed in a legend. If omitted, there will be no legend. The length of this sequence should be the same as the length of datasets.

CodeSkulptor3 implements two other custom modules. The Numeric module is for mathematics with two-dimensional matrices. The CodeSkulptor module is a small collection of miscellaneous operations. To use these operations, first import the appropriate module with import numeric or import codeskulptor.

Operations:
Superclass:

The Numeric module is for mathematics with two-dimensional matrices. It provides some of the basic operations of linear algebra. Matrices are restricted to only contain numbers. This module is not a part of standard Python, rather it is a simpler and lighter weight module than the commonly used NumPy module. To use these operations, first import the module with import numeric.

Syntax:
numeric.Matrix(data)

Example:
CodeOutput
import numeric

print(numeric.Matrix([[0, 1], [3, 7], [5, 2]]))
[[0, 1],
 [3, 7],
 [5, 2]]

Returns a 2-dimensional matrix object corresponding to the given data, which must be a sequence of sequences.

Syntax:
numeric.identity(size)

Example:
CodeOutput
import numeric

print(numeric.identity(3))
[[1, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]

Returns a size×size 2-dimensional identity matrix.

Syntax:
a_matrix[(i, j)]
a_matrix.__getitem__((i, j))

Example:
CodeOutput
import numeric

print(numeric.identity(3)[(0, 0)])
1.0

Returns the value in the matrix a_matrix at row i and column j.

Syntax:
a_matrix.getrow(i)

Example:
CodeOutput
import numeric

print(numeric.identity(3).getrow(1))
[[0, 1, 0]]

If the given matrix a_matrix has dimensions m×n, then the result is a new 1×n matrix that is a copy of row i of the matrix.

Syntax:
a_matrix.getcol(j)

Example:
CodeOutput
import numeric

print(numeric.identity(3).getcol(2))
[[0, 0, 1]]

If the given matrix a_matrix has dimensions m×n, then the result is a new 1×m matrix that is a copy of column j of the matrix.

Syntax:
a_matrix[(i, j)] = value
a_matrix.__setitem__((i, j), value)

Example:
CodeOutput
import numeric

matrix = numeric.identity(3)
matrix[(0, 0)] = 5
print(matrix)
[[5, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]
Style:
Avoid using a_matrix.__setitem__().

Sets the value in the matrix a_matrix at row i and column j to be value value.

Syntax:
matrix1 + matrix2

Example:
CodeOutput
import numeric

matrix = numeric.identity(3)
print(matrix + matrix)
[[2, 0, 0],
 [0, 2, 0],
 [0, 0, 2]]

Adds two m×n matrices. The result is a new m×n matrix.

Syntax:
matrix1 - matrix2

Example:
CodeOutput
import numeric

matrix = numeric.identity(3)
print(matrix - matrix)
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]

Subtracts m×n matrix matrix2 from m×n matrix matrix1. The result is a new m×n matrix.

Syntax:
matrix1 @ matrix2

Example:
CodeOutput
import numeric

matrix1 = numeric.Matrix([[1, 2]])
matrix2 = numeric.Matrix([[3, 4, 5], [6, 7, 8]])
print(matrix1 @ matrix2)
[[15, 18, 21]]

Muliplies m×n matrix matrix1 by n×p matrix matrix2. The result is a new m×p matrix.

Syntax:
a_matrix * factor
factor * a_matrix

Example:
CodeOutput
import numeric

matrix = numeric.Matrix([[3, 4, 5], [6, 7, 8]])
print(matrix * 2)
[[6, 8, 10],
 [12, 14, 16]]

Given a m×n matrix and a number factor, it returns a new m×n matrix where each original element has been multiplied by factor.

Syntax:
a_matrix.copy()

Example:
CodeOutput
import numeric

matrix1 = numeric.Matrix([[1, 2]])
matrix2 = matrix1.copy()
matrix2[(0, 0)] = 5
print(matrix1)
[[1, 2]]

Makes a new matrix with the same elements as a_matrix.

Syntax:
a_matrix.inverse()

Example:
CodeOutput
import numeric

matrix = numeric.Matrix([[1, 0], [1, 2]])
print(matrix.inverse())
[[1, 0],
 [-0.5, -0.5]]

Given a n×n matrix a_matrix, it returns its n×n matrix inverse, if it exists. Inverses exist only for some square matrices. If no inverse exists, an error is raised.

Syntax:
a_matrix.transpose()

Example:
CodeOutput
import numeric

matrix = numeric.Matrix([[1, 2]])
print(matrix.transpose())
[[1],
 [2]]

Given a m×n matrix a_matrix, it returns its n×m matrix transpose. I.e., if a value is in the original matrix at row i and column j, then it is at row j and column i in its transpose.

Syntax:
a_matrix.abs()

Example:
CodeOutput
import numeric

matrix = numeric.Matrix([[1, -2, -5]])
print(matrix.abs())
[[1, 2, 5]]

Given a m×n matrix a_matrix, it returns a new m×n matrix consisting of the absolute values of each of the original elements.

Syntax:
a_matrix.summation()

Example:
CodeOutput
import numeric

matrix = numeric.Matrix([[1, -2, -5], [4, -2, 0]])
print(matrix.summation())
-4.0

Returns the sum of all the elements in the matrix a_matrix.

Syntax:
a_matrix.shape()

Example:
CodeOutput
import numeric

matrix = numeric.Matrix([[1, -2, -5], [4, -2, 0]])
print(matrix.shape())
(2, 3)

Given a m×n matrix a_matrix, it returns the pair (2-tuple) (m, n).

Operations:

The CodeSkulptor module is a small collection of miscellaneous operations that are not in standard Python. To use these operations, first import the module with import codeskulptor.

Syntax:
codeskulptor.file2url(filename)

Example:
CodeOutput
import urllib2
import codeskulptor

a_file = urllib2.urlopen(codeskulptor.file2url('assets-Quick_fox.txt'))
print(a_file.read())
The quick brown fox jumped over the lazy dog.
See also:
urllib2.urlopen — Opening text file
simplegui.load_image — Loading image file
simplegui.load_sound — Loading sound file

Returns a standard CodeSkulptor URL for the given filename. Such a URL is would be used as an argument to any function that opens a file. This allows you to abbreviate the URL for many files provided by the CodeSkulptor authors. This does not check whether the filename or URL exists.

Syntax:
codeskulptor.randomize_iteration(randomize=boolean)

Example:
CodeOutput
import codeskulptor

codeskulptor.randomize_iteration(randomize=True)
s = {1, 2, 3}
for element in s:
    print(element)
for element in s:
    print(element)
# One possible result
2
1
3
3
2
1

Sets a global system flag to the given value of randomize. By default, this flag is True.

When this flag is True, any iteration on dictionaries and sets is randomized, to emphasize that code should not depend upon the iteration ordering. When this flag is False, the iteration order is determined in some implementation-dependent way.

CodeSkulptor3 is a browser-based programming environment for the programming language Python. CodeSkulptor3 runs in modern versions of Google Chrome, Mozilla Firefox, and Apple Safari. Some features may work in other browsers, such as Microsoft Internet Explorer, but do not expect full functionality.

The CodeSkulptor window consists of the following elements.

The control area is either on the left or the top, depending on the window dimensions, which consists of buttons for the main CodeSkulptor features: Run, Reset, Save, New URL, Download, Load, Join, the documentation you are currently reading, , and information about CodeSkulptor.

The left side of the main part of the page is an editor for typing in Python programs. Keyboard shortcuts are described below for Windows, Mac OS, and Linux. Also, if you double-click an identifier or other piece of text, it will highlight all the matching text.

The right side of the main part of the page is the console. When you run the program in the editor, its printed output and error messages are displayed here. The console output can be reset.

The vertical bar between the two main parts of the window can be adjusted to the left or right.

Runs the Python code that is in the CodeSkulptor editor. Prints the results of any print statement and any error messages to the CodeSkulptor console. If you use the SimpleGUI module, your program can create a pop-up interactive window.

While the program is running, this button becomes a "Pause" button. You can pause the execution of your program at any time and the currently executing line of code will be highlighted in the editor. The editor will be read-only while the program is paused and this button becomes a "Resume" button. While paused, you can either resume the program or use the "Reset" button to end the execution of the program.

Clears the CodeSkulptor console and closes any pop-up windows created by CodeSkulptor.

Saves the contents of the CodeSkulptor editor to “cloud”-based storage. It also changes the URL shown in the browser to be one where you can access this program again. One way to remember this URL is to bookmark it in your browser.

The last part of this URL is a version number — each successive save will create a new version. Thus, each saved version is available from its own URL.

After saving, you can download the program to a file on your own computer.

On each save the URL for your program increases in version number. This button creates a new URL independent of the previous one.

Downloads a just-saved program to your own computer. This button is only active after you have saved this program and before you modify it further.

Loads a Python file from your own computer into the CodeSkulptor editor.

Allows you to create or join a collaborative editing session with others. This button will open a dialog box allowing you to enter the session ID of an existing collaborative editing session. If you leave it blank, a new session will be created.

In a collaborative editing session, the session ID will be displayed in the upper left corner of the window. You can send that session ID to others to allow them to join your session. The upper right corner of the window will display all of the users currently in the session. You can click your user to change your display name from the default.

Once in a collaborative editing session, this button becomes a "Leave" button that allows you to leave the session. You can then rejoin it later, if you desire.

Collaborative editing sessions are not permanent, and will be deleted in a day or so. Your work is not saved. Note, however, that anyone in a collaborative editing session can save the work at any time using the save button. If one person saves the file, that does not show up in any one else's editor. You either need to share the link with each other or each save your own copy.

(Chrome, Safari) Alt‑RRun Python program.
(Chrome, Safari) Alt‑SSave Python program.
(Chrome, Safari) Alt‑XReset Python program.
(Firefox) Alt‑Shift‑RRun Python program.
(Firefox) Alt‑Shift‑SSave Python program.
(Firefox) Alt‑Shift‑XReset Python program.
Left ArrowMove to the left one character.
Right ArrowMove to the right one character.
Up ArrowMove up one line.
Down ArrowMove down one line.
EndGo to the end of the current line.
HomeGo to the beginning of the current line.
PageUpMove up one page.
PageDownMove down one page.
Ctrl‑HomeGo to the beginning of the current page.
Alt‑UpGo to the beginning of the current page.
Ctrl‑EndGo to the end of the current page.
Ctrl‑DownGo to the end of the current page.
Ctrl‑LeftMove left one word.
Ctrl‑RightMove right one word.
Alt‑LeftGo to the start of current line.
Alt‑RightGo to the end of current line.
DeleteDelete character on the right.
BackspaceDelete character on the left.
InsertOverwrite characters on and after current location.
Ctrl‑DDelete current line.
Ctrl‑BackspaceDelete word to the left.
Ctrl‑DeleteDelete word to the right.
Ctrl‑KComment all selected lines.
Ctrl‑Shift‑KUncomment all selected lines.
Ctrl‑ASelect all
Ctrl‑CCopy selected area
Ctrl‑XCut selected area
Ctrl‑VPaste
Ctrl‑ZUndo
Shift‑Ctrl‑ZRedo
Ctrl‑YRedo
TabIndent right. Shifts cursor over to the next tab stop.
Shift‑Tab“Smart” indent right. Shifts cursor over to the appropriate indentation given the context of the program.
Ctrl‑[Indent left. Shifts cursor over left to the previous tab stop.
Ctrl‑]Indent right. Shifts cursor over right to{'key': the next tab stop.
Cntl‑FStart Searching
Cntl‑GFind Next
Shift‑Cntl‑GFind Previous
Shift‑Cntl‑FReplace Once
Shift‑Cntl‑RReplace All
(Chrome, Firefox, Safari) Ctrl‑Opt‑RRun Python program.
(Chrome, Firefox, Safari) Ctrl‑Opt‑SSave Python program.
(Chrome, Firefox, Safari) Ctrl‑Opt‑XReset Python program.
LeftMove to the left one character.
RightMove to the right one character.
UpMove up one line.
DownMove down one line.
Cmd‑UpGo to the beginning of the current page.
Cmd‑DownGo to the end of the current page.
Cmd‑LeftGo to the start of the current line.
Cmd‑RightGo to the end of the current line.
Alt‑LeftMove left one word.
Alt‑RightMove right one word.
Ctrl‑BMove to the left one character.
Ctrl‑FMove to the right one character.
Ctrl‑PMove up one line.
Ctrl‑NMove down one line.
Alt‑BMove left one word.
Alt‑FMove right one word.
Ctrl‑AGo to the start of the current line.
Ctrl‑EGo to the end of the current line.
Ctrl‑VMove up one page.
Shift‑Ctrl‑VMove down one page.
DeleteDelete character on the left.
Cmd‑DDelete current line.
Ctrl‑HDelete character on the left.
Ctrl‑DDelete character on the right.
Alt‑DeleteDelete word on the left.
Alt‑DDelete word on the right.
Ctrl‑KComment all selected lines.
Ctrl‑Shift‑KUncomment all selected lines.
Cmd‑ASelect all
Cmd‑CCopy selected area
Cmd‑XCut selected area
Cmd‑VPaste
Cmd‑ZUndo
Shift‑Cmd‑ZRedo
Cmd‑YRedo
Ctrl‑TSwap positions of the character to the left and the character to the right of the cursor.
TabIndent right. Shifts cursor over to the next tab stop.
Shift‑Tab“Smart” indent right. Shifts cursor over to the appropriate indentation given the context of the program.
Cmd‑[Indent left. Shifts cursor over left to the previous tab stop.
Cmd‑]Indent right. Shifts cursor over right to the next tab stop.
Cmd‑FStart Searching
Cmd‑GFind Next
Shift‑Cmd‑GFind Previous
Cmd‑Option‑FReplace Once
Shift‑Cmd‑Option‑FReplace All
(Chrome) Alt‑RRun Python program.
(Chrome) Alt‑SSave Python program.
(Chrome) Alt‑XReset Python program.
(Firefox) Alt‑Shift‑RRun Python program.
(Firefox) Alt‑Shift‑SSave Python program.
(Firefox) Alt‑Shift‑XReset Python program.
Left ArrowMove to the left one character.
Right ArrowMove to the right one character.
Up ArrowMove up one line.
Down ArrowMove down one line.
EndGo to the end of the current line.
HomeGo to the beginning of the current line.
PageUpMove up one page.
PageDownMove down one page.
Ctrl‑HomeGo to the beginning of the current page.
Alt‑UpGo to the beginning of the current page.
Ctrl‑EndGo to the end of the current page.
Ctrl‑DownGo to the end of the current page.
Ctrl‑LeftMove left one word.
Ctrl‑RightMove right one word.
Alt‑LeftGo to the start of current line.
Alt‑RightGo to the end of current line.
DeleteDelete character on the right.
BackspaceDelete character on the left.
InsertOverwrite characters on and after current location.
Ctrl‑DDelete current line.
Ctrl‑BackspaceDelete word to the left.
Ctrl‑DeleteDelete word to the right.
Ctrl‑KComment all selected lines.
Ctrl‑Shift‑KUncomment all selected lines.
Ctrl‑ASelect all
Ctrl‑CCopy selected area
Ctrl‑XCut selected area
Ctrl‑VPaste
Ctrl‑ZUndo
Shift‑Ctrl‑ZRedo
Ctrl‑YRedo
TabIndent right. Shifts cursor over to the next tab stop. Any new lines after the shifted current line will automatically start where the shifted line began.
Shift‑TabIndent right. Shifts cursor over to the next tab stop. Any new lines after the shifted current line will start at the beginning left margin.
Ctrl‑[Indent left. Shifts cursor over left to the previous tab stop.
Ctrl‑]Indent right. Shifts cursor over right to the next tab stop.
Ctrl‑FStart Searching
Ctrl‑GFind Next
Shift‑Ctrl‑GFind Previous
Shift‑Ctrl‑FReplace Once
Shift‑Ctrl‑RReplace All