Sequences

Sequences are ordered sets of objects indexed by non-negative integers. Sequences include string, list, tuple, and range objects. Lists and tuples are sequences of arbitrary objects, whereas strings are sequences of characters. However, string, tuple, and range objects are immutable, whereas, the list object is mutable. All sequence types have a number of operations in common. Note that, for the immutable types, any operation will only return a value rather than actually change the value.

For all sequences, the indexing and slicing operators apply as described in the previous chapter. The string and list data types were discussed in detail in Chapter 1Python Objects, Types, and Expressions. Here, we present some of the important methods and operations that are common to all of the sequence types (string, list, tuple, and range objects).

All sequences have the following methods:

Method

Description

len(s)

Returns the number of elements in s.

min(s,[,default=obj, key=func])

Returns the minimum value in s (alphabetically for strings).

max(s,[,default=obj, key=func])

Returns the maximum value in s (alphabetically for strings).

sum(s,[,start=0])

Returns the sum of the elements (returns TypeError if s

is not numeric).

all(s)

Returns True if all elements in s are True (that is, not 0, False, or Null).

any(s)

Checks whether any item in s is True.

 

In addition, all sequences support the following operations:

Operation

Description

s+r

Concatenates two sequences of the same type.

s*n

Makes n copies of s, where n is an integer.

v1,v2...,vn=s

Unpacks n variables from s to v1, v2, and so on.

s[i]

Indexing returns the i element of s.

s[i:j:stride]

Slicing returns elements between i and j with optional stride.

x in s

Returns True if the x element is in s.

x not in s

Returns True if the x element is not in s.

 

Let's consider an example code snippet implementing some of the preceding operations on the list data type :

>>>list() # an empty list   
>>>list1 = [1,2,3, 4]
>>>list1.append(1) # append value 1 at the end of the list
>>>list1
[1, 2, 3, 4, 1]
>>>list2 = list1 *2
[1, 2, 3, 4, 1, 1, 2, 3, 4, 1]
>>> min(list1)
1
>>> max(list1)
4
>>>list1.insert(0,2) # insert an value 2 at index 0
>>> list1
[2, 1, 2, 3, 4, 1]
>>>list1.reverse()
>>> list1
[1, 4, 3, 2, 1, 2]
>>>list2=[11,12]
>>>list1.extend(list2)
>>> list1
[1, 4, 3, 2, 1, 2, 11, 12]
>>>sum(list1)
36
>>> len(list1)
8
>>> list1.sort()
>>> list1
[1, 1, 2, 2, 3, 4, 11, 12]
>>>list1.remove(12) #remove value 12 form the list
>>> list1
[1, 1, 2, 2, 3, 4, 11]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset