| Python Library Reference |
There are six sequence types: strings, Unicode strings, lists,tuples, buffers, and xrange objects.
Strings literals are written in single or double quotes:'xyzzy',"frobozz". See chapter 2 of thePython Reference Manual for more aboutstring literals. Unicode strings are much like strings, but arespecified in the syntax using a preceeding "u" character:u'abc',u"def". Lists are constructed with square brackets,separating items with commas:[a, b, c]. Tuples areconstructed by the comma operator (not within square brackets), withor without enclosing parentheses, but an empty tuple must have theenclosing parentheses, e.g.,a, b, c or(). A singleitem tuple must have a trailing comma, e.g.,(d,).
Buffer objects are not directly supported by Python syntax, but can becreated by calling the builtin functionbuffer(). They support concatenationand repetition, but the result is a new string object rather than anew buffer object.
Xrange objects are similar to buffers in that there is no specificsyntax to create them, but they are created using thexrange() function. They don't supportslicing or concatenation, but do support repetition, and usingin,not in,min() ormax() on themis inefficient.
Most sequence types support the following operations. The "in" and"not in" operations have the same priorities as the comparisonoperations. The "+" and "*" operations have the samepriority as the corresponding numeric operations.2.7
This table lists the sequence operations sorted in ascending priority(operations in the same box have the same priority). In the table,s andt are sequences of the same type;n,iandj are integers:
| Operation | Result | Notes |
|---|---|---|
x ins | 1 if an item ofs is equal tox, else0 | |
x not ins | 0 if an item ofs isequal tox, else1 | |
s +t | the concatenation ofs andt | |
s *n ,n *s | n shallow copies ofs concatenated | (1) |
s[i] | i'th item ofs, origin 0 | (2) |
s[i:j] | slice ofs fromi toj | (2), (3) |
len(s) | length ofs | |
min(s) | smallest item ofs | |
max(s) | largest item ofs |
Notes:
0 are treated as0 (which yields an empty sequence of the same type ass). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:>>> lists = [[]] * 3>>> lists[[], [], []]>>> lists[0].append(3)>>> lists[[3], [3], [3]]
What has happened is thatlists is a list containing three copies of the list[[]] (a one-element list containing an empty list), but the contained list is shared by each copy. You can create a list of different lists this way:
>>> lists = [[] for i in range(3)]>>> lists[0].append(3)>>> lists[1].append(5)>>> lists[2].append(7)>>> lists[[3], [5], [7]]
len(s) +i orlen(s) +j is substituted. But note that-0 is still0.i <=k <j. Ifi orj is greater thanlen(s), uselen(s). Ifi is omitted, use0. Ifj is omitted, uselen(s). Ifi is greater than or equal toj, the slice is empty.| Python Library Reference |