Python Types and Operators


Simple Data Types: Numbers


Python Operations

Operators (in descending precedence)Description
(...), [...], {...}, `...`Tuple, list, dictionary, conversion to string
x[i], x[i:j], x.y, x(...)Indexing, slicing, qualification, function call
-x, +x, ~xUnary negation, unary identity, bitwise complement
x * y, x / y, x % ymultiplication, division, remainder or format
x + y, x - yaddition or concatenation, subtraction
x << y, x >> yShift left y bits, shift right y bits
x & yBitwise and
x ^ yBitwise exclusive or
x | yBitwise or
<, <=, >, >=, <>, !=,
is, is not,
in, not in
Comparison operators,
identity tests,
sequence membership
not xlogical negation
x and yLogical and (with shortcut evaluation)
x or y Logical or (with shortcut evaluation)
lambda args: expression anonymous function

Mixed mode:

When arithmetic is performed on mixed-type operands, e.g. 3.14 * 3, Python converts the simpler type to the more complex type. In this case, a copy of the 3 is converted to 3.00, then double arithmetic is performed, and the result is a double, 9.42.

Operator Overloading:

Note that the operators +, *, and % are overloaded.


Standard Data Structures


Strings

String ExampleExplanation
'This is a "string."'Strings may be enclosed in apostrophes.
"This is today's second string."Strings may be enclosed in quotation marks.
"""This is
a
multiline string."""
Strings enclosed in triple quotation marks may span several lines.
"A"There is no char type; for characters, use a single-character string.
'' or ""The empty string.


Strings are immutable. You cannot modify a string.
Instead, slice the string and recombine, creating a new string.

Operations on Strings

OperationExplanation
str1 + str2Concatenation
str * 5Repetition
str[i]Indexing. (Counts from zero. Negative index
counts from right end.)
str[i:j]Slicing. (From ith element to just before the jth)
(The subscripts actually indicate the slice points, not the string elements.)
len(str)String length
"There were %d sparrows and %d crows left." % (sparrow_ct, crow_ct)String formatting
for char in str:Iteration through a string's members
"C" in strString membership

String Formatting Codes (Same as printf codes in C):

CodeDescription
%sString
%dDecimal (int)
%iInteger
%uUnsigned (int)
%OOctal integer
%xHex integer
%eFloating point scientific notation
%fDecimal (float)
%%Literal %

String Escape Sequences (same as in C)

CodeMeaning
\newlineIgnore newline
\\Backslash
\'Apostrophe
\"Quotation mark
\aBell ("alarm")
\bBackspace
\eEscape
\000Null (Don't use to end a string in Python!)
\nNewline (linefeed)
\vVertical tab
\tTab (horizontal)
\rCarriage return
\fFormfeed
\0XXOctal value XX
\xXXHex value XX
\otherAny other character

Also note: Many useful string functions are contained in the string module.


Lists

Operations on Lists

OperationInterpretation
li1 = [ ]Assigning an empty list
li2 = [14, 22, -8, 0]Assigning a list of 4 items.
li3 = [4, "xyz", [4-5j, 0] ]Nested lists
lis[i], lis1[j][k]Indexing a list
lis[i:j]Slicing a list
len(lis1)Length of a list
lis1 + lis2Concatenate lists
lis * 4Repeat a list
for x in lis:Iterate through a list
x in lisList membership
lis.append(item)Append item to list.
lis.sort()Sort list.
lis.index(5)Search for index of 5 in lis.
lis.reverse()Reverse elements of lis.
del lis[5]Remove lis[5] from list.
lis[5:9] = [ ]Remove 5th through 8th elements from lis.
lis[k] = 7Assignment by index
lis[j:k] = [4, 5, 6]Assignment by slice
range(5)Returns list [0, 1, 2, 3, 4]
range(4, 7)Returns list [4, 5, 6]

Dictionaries

Dictionaries are similar to lists, except, instead of subscripts, dictionaries use keys.

Operations on Dictionaries

OperationInterpretation
{ }Empty dictionary
dic1 = {'spam':5, 'eggs':10}Two-item dictionary.
'spam' and 'eggs' are the keys.
dic2 = {'food': {'ham':1, 'egg':2}}Nested dictionaries
dic1['spam'], dic2['food']['egg']Indexing by key
dic1.has_key('eggs')Membership test method
dic1.keys()Method returns list of keys.
dic1.values()Method returns list of values.
len(dic2)Returns number of elements of dic2.
dic3[key] = valueChanges element of dic3.
del dic3[key]Deletes an element from dic3.

Tuples

Tuples are, in effect, immutable lists. Thus, accessing data within tuples is fast, but changes require creation of new tuples.

OperationInterpretation
( )An empty tuple
tup1 = (4,)A one-item tuple. The comma distinguishes it from a numerical expression.
tup2 = (0, 1, 2, 4)A four-item tuple
tup2 = 0, 1, 2, 4Another four-item tuple
tup3 = ('the', ('and', 'you'))Nested tuples
tup1[2], tup3[j][k]Indexing
tup2[2:4]Slicing
len(tup2)Length
tup1 + tup2Concatenation
tup2 * 3Repetition
for item in tup2:Iteration through a tuple
4 in tup2Membership

Files

OperationInterpretation
output = open('/tmp/spam', 'w')Create output file object, for writing file /tmp/spam.
input = open('foo', 'r')Create input file object, for reading file foo.
big_str = input.read( )Read entire input file into big_str.
str = input.read(N)Read N bytes from input into str.
str = input.readline()Read next line (through end-of-line marker) into str.
str_list = input.readlines()Read entire file into a list of strings.
output.write(str)Write string str onto file.
output.writelines(str_list)Write all strings in str_list onto file.
output.close()Manual close of file. Close is also done automatically when file object goes out of scope (when collected).

Miscellaneous Stuff


References

Python variables are references to stuff. Several variables may refer to the same object.

Assignment creates references, not copies.


Comparisons, Equality, and Truth

Object Truth Values

Zero is False, non-zero is true. Any empty data structure is False; a non-empty structure is True. None is a null data structure, and is False.

ObjectValue
"bar"True
""False
[ ]False
{ }False
1True
0.0False
noneFalse

Next: Python Statements

Go back to First Python Page.