Python Essentials: Operators and Expressions | 3 | WebReference

Python Essentials: Operators and Expressions | 3

'; figDoc.write(zhtm); figDoc.close(); } // modified 3.1.99 RWE v4.1 -->

Python Essentials: Operators and Expressions

Operations on Dictionaries

Dictionaries provide a mapping between names and objects. You can apply the following operations to dictionaries:

Operation

Description

x = d[k]

Indexing by key

d[k] = x

Assignment by key

del d[k]

Deletes an item by key

len(d)

Number of items in the dictionary


Key values can be any immutable object, such as strings, numbers, and tuples. In addition, dictionary keys can be specified as a comma-separated list of values, like this:

d = { }
d[1,2,3] = "foo"
d[1,0,3] = "bar"

In this case, the key values represent a tuple, making the preceding assignments identical to the following:

d[(1,2,3)] = "foo"
d[(1,0,3)] = "bar"

Operations on Sets

The set and frozenset type support a number of common set operations:

Operation

Description

s | t

Union of s and t

s & t

Intersection of s and t

s – t

Set difference

s ^ t

Symmetric difference

len(s)

Number of items in the set

max(s)

Maximum value

min(s)

Minimum value


Augmented Assignment

Python provides the following set of augmented assignment operators:

Operation

Description

x += y

x = x + y

x -= y

x = x - y

x *= y

x = x * y

x /= y

x = x / y

x //= y

x = x // y

x **= y

x = x ** y

x %= y

x = x % y

x &= y

x = x & y

x |= y

x = x | y

x ^= y

x = x ^ y

x >>= y

x = x >> y

x <<= y

x = x << y


These operators can be used anywhere that ordinary assignment is used. For example:

a = 3
b = [1,2]
c = "Hello %s %s"
a += 1                    # a = 4
b[1] += 10                # b = [1, 12]
c %= ("Monty", "Python")  # c = "Hello Monty Python"

Augmented assignment doesn't violate mutability or perform in-place modification of objects. Therefore, writing x += y creates an entirely new object x with the value x + y. User-defined classes can redefine the augmented assignment operators using the special methods described in Chapter 3, "Types and Objects."

The Attribute (.) Operator

The dot (.) operator is used to access the attributes of an object. For example:

foo.x = 3
print foo.y
a = foo.bar(3,4,5)

More than one dot operator can appear in a single expression, such as in foo.y.a.b. The dot operator can also be applied to the intermediate results of functions, as in a = foo.bar(3,4,5).spam.

Type Conversion

Sometimes it's necessary to perform conversions between the built-in types. To convert between types you simply use the type name as a function. In addition, several built-in functions are supplied to perform special kinds of conversions. All of these functions return a new object representing the converted value.

Function

Description

int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

float(x)

Converts x to a floating-point number.

complex(real [,imag])

Creates a complex number.

str(x)

Converts object x to a string representation.

repr(x)

Converts object x to an expression string.

eval(str)

Evaluates a string and returns an object.

tuple(s)

Converts s to a tuple.

list(s)

Converts s to a list.

set(s)

Converts s to a set.

dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.

frozenset(s)

Converts s to a frozen set.

chr(x)

Converts an integer to a character.

unichr(x)

Converts an integer to a Unicode character.

ord(x)

Converts a single character to its integer value.

hex(x)

Converts an integer to a hexadecimal string.

oct(x)

Converts an integer to an octal string.


You also can write the repr(x) function using backquotes as ´x´. Note that the str() and repr() functions may return different results. repr() typically creates an expression string that can be evaluated with eval() to re-create the object. On the other hand, str() produces a concise or nicely formatted representation of the object (and is used by the print statement). The ord() function returns the integer ordinal value for a standard or Unicode character. The chr() and unichr() functions convert integers back into standard or Unicode characters, respectively.

To convert strings back into numbers and other objects, use the int(), long(), and float() functions. The eval() function can also convert a string containing a valid expression to an object. Here's an example:

a = int("34")             # a = 34
b = long("0xfe76214", 16) # b = 266822164L (0xfe76214L)
b = float("3.1415926")    # b = 3.1415926
c = eval("3, 5, 6")       # c = (3,5,6)

In functions that create containers (list(), tuple(), set(), and so on), the argument may be any object that supports iteration that is used to generate all the items used to populate the object that's being created.

Created: March 27, 2003
Revised: March 13, 2006

URL: http://webreference.com/programming/python/1