Python - Sequence (type)

Card Puncher Data Processing

About

The following data structure are sequence:

Comparison

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII ordering for individual characters.

Example

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

Packing

  • Sequence packing: The values 12345, 54321 and 'hello!' are packed together in a tuple
t = 12345, 54321, 'hello!' 
  • Sequence unpacking: The reverse packing operation
x, y, z = t

Sequence unpacking works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence.

Multiple assignment is really just a combination of tuple packing and sequence unpacking

Modification while iterating

To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended to first make a copy. The slice notation makes this especially convenient:

words = ['cat', 'window', 'defenestrate']
for w in words[:]:  # Loop over a slice copy of the entire list.
     if len(w) > 6:
         words.insert(0, w)

words
['defenestrate', 'cat', 'window', 'defenestrate']

Iteration

Enumerate (index and value)

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
     print i, v
0 tic
1 tac
2 toe

over two or more sequences

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print 'What is your {0}?  It is {1}.'.format(q, a)
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

in reverse order

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

for i in reversed(xrange(1,10,2)):
     print i
9
7
5
3
1

in sorted order

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
     print f
apple
banana
orange
pear

Documentation / Reference





Discover More
Imperative Vs Functional
Functional Programming - Map

A page the map functional programming function The map method creates a new collection with the results of calling a provided function on every element in the collection. The map operation produces...
Imperative Vs Functional
Functional Programming / Collection - Filter

filtering in functional programming functional interface
Card Puncher Data Processing
Python - Collection

collection in Python: Data Type: Type Sequence (Ordered) Mutable Duplicate Yes Yes Yes Yes No Yes No Yes No No Yes No
Card Puncher Data Processing
Python - Comprehension (Iteration)

Comprehension are a way to loop over elements of: a , , , tuple, , or . Comprehensions permit to build collections out of other collections. Comprehensions allow one to express computations...
Card Puncher Data Processing
Python - Filter Function

The filter implementation in Python. Filter applies a function individually to each element in a series; however, with filter, this function evaluates to True or False and only elements that evaluate...
Card Puncher Data Processing
Python - List

Lists are used to store a collection of different pieces of information in a sequence order of under a single variable name. A list can be used to implement a . A list is mutable whereas a tuple is not....
Card Puncher Data Processing
Python - Map Function

The implementation in Python. Map transforms a series of elements by applying a function individually to each element in the series. It then returns the series of transformed elements. For the map...
Card Puncher Data Processing
Python - Range (sequence of integer)

A range represents a sequence of integer, it is not a list or a set. To get a list of a set from a range, you have to use the constructor: list() or set(). For any integer n, range(n) represents...
Card Puncher Data Processing
Python - Slice Notation

Slicing (sub-list) returns a list of elements in a sequence from the position a to the positionbefore b. where in the sequence[a:b:c]: a is the first element of the slice. It can be negative (ie...
Card Puncher Data Processing
Python - String (str type)

in Python A string literal is a sequence data type. Strings in Python are: sequence with characters as elements Each character in a string has a subscript or offset (id). The number starts at...



Share this page:
Follow us:
Task Runner