Operations on sequence types Flashcards
What is sequence?
It is an object which consists of sequential elements or other objects through which you can iterate.
Name all sequence data types in python.
- strings;
- Unicode strings;
- lists;
- tuples;
- bytearrays;
- buffers;
- xrange objects.
What are bytearrays?
It is a mutable sequence of bytes.
A bytearray is very similar to a regular python string (str in python2.x, bytes in python3) but with an important difference, whereas strings are immutable, bytearrays are mutable, a bit like a list of single character strings.
What are buffers?
buffer(object[, offset[, size]])
A new buffer object will be created which references the object argument.
An example usage:
> > > s = ‘Hello world’
t = buffer(s, 6, 5)
t
> > > print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn’t take extra storage space - it references a slice of the string.
This isn’t very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:
> > > s = bytearray(1000000) # a million zeroed bytes
t = buffer(s, 1) # slice cuts off the first byte
s[1] = 5 # set the second element in s
t[0] # which is now also the first element in t!
‘\x05’
How to check if an item is equal or not to x?
x in s # true if x the items of x
x not in s
How to perform concatenation (addition) of two sequences of the same type?
s + t
What are next operations?
»> s * n
»> n * s
They are equivalent to adding s to itself n times.
How to get ith item of s by it’s index?
s[i] # indexation starts from zero, 0 is the first element
How to slice s from i to j? (excluding jth element)
s[i:j]
How to slice s from i to j with step k (selecting every kth item)? (excluding jth element)
s[i:j:k]
> > > s = ‘0123456789’
s[0:7:3]
‘036’
Get every second element in
s = ‘0123456789’
starting from zero.
s[::2]
What can happen in case you do next:
»> l = [‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’]
»> del l[4:9]
Those elements gonna be removed from the object:
»> l
[‘0’, ‘1’, ‘2’, ‘3’, ‘9’]
Get length of the sequence s.
len(s)
Get smallest item of s.
min(s)
Get largest item of s.
max(s)