15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

obj not in seq Tests if obj is not a member of sequence seq<br />

Membership (in, not in)<br />

Membership test operators are used to determine whether an element is in or is a member of a<br />

sequence. For strings, this test is whether a character is in a string, and for lists and tuples, it is whether<br />

an object is an element of those sequences. The in and not in operators are Boolean in nature; they<br />

return true if the membership is confirmed and False otherwise.<br />

The syntax for using the membership operators is as follows:<br />

obj [not] in sequence<br />

Concatenation (+)<br />

This operation allows us to take one sequence and join it with another sequence of the same type. The<br />

syntax for using the concatenation operator is as follows:<br />

sequence1 + sequence2<br />

The resulting expression is a new sequence that contains the combined contents of sequences<br />

sequence1 and sequence2. Note, however, that although this appears to be the simplest way<br />

conceptually to merge the contents of two sequences together, it is not the fastest or most efficient.<br />

For strings, it is less memory-intensive to hold all of the substrings in a list or iterable and use one final<br />

join() string method call to merge them together. Similarly for lists, it is recommend that readers use<br />

the extend() list method instead of concatenating two or more lists together. Concatenation comes in<br />

handy when you need to merge two sequences together on the fly and cannot rely on mutable object<br />

built-in methods that do not have a return value (or more accurately, a return value of None). There is<br />

an example of this case in the section below on slicing.<br />

Repetition ( * )<br />

The repetition operator is useful when consecutive copies of sequence elements are desired. The syntax<br />

for using the repetition operator is as follows:<br />

sequence * copies_int<br />

The number of copies, copies_int, must be an integer (prior to 1.6, long integers were not allowed). As<br />

with the concatenation operator, the object returned is newly allocated to hold the contents of the<br />

multiply replicated objects.<br />

Slices ( [ ], [ : ], [ : : ] )<br />

To put it simply: sequences are data structures that hold objects in an ordered manner. You can get<br />

access to individual elements with an index and pair of brackets, or a consecutive group of elements

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!