In Python, a sequence is a collection of items, that:
- Is Ordered — sequences are ordered collections of items, meaning that each item has a specific position in the sequence (e.g.
[0, 1, 2, 3]
); - Is Indexed — lookups for individual items in a sequence are done by their index, which are integer values that represent the position of the item in the sequence (e.g.
seq[0]
); - Has Length — sequences have a length, which gives you the total number of items it contains (e.g.
len(seq)
); - Is Iterable — individual items in a sequence can be iterated over using a loop (e.g.
for item in sequence: ...
);
For example, you can see how these properties apply to a list (which is one of several types of sequences in Python):
my_list = [1, 2, 3, 4]
# indexed
print(my_list[1]) # 2
# has length
print(len(my_list)) # 4
# ordered, iterable
for item in my_list:
print(item) # 1 2 3 4
#Sequence Types
There are several types of sequences in Python, including lists, tuples, range objects, strings, and binary sequence types (i.e. bytes, bytearrays and memoryview).
Please note that sets and dictionaries are not considered to be sequences. This is because a set is an unordered collection of unique items, while a dictionary is a map that uses arbitrary immutable keys for lookups rather than integers.
#Common Sequence Operations
There are some common operations that can be performed on sequences, such as:
- Slicing — a range of items in a sequence can be sliced (e.g.
seq[0:2]
); - Concatenation — multiple sequences can be joined together using the
+
operator (e.g.[1] + [2]
); - Repetition — a sequence can be repeated using the
*
operator (e.g.'foo' * 3
); - Membership — using the
in
operator, individual items can be checked to see if they are in a sequence (e.g.1 in [1, 2, 3]
); - Comparison — sequences of the same type can be compared (e.g.
[1, 2] == [1, 2]
);
Consider, for example, the following list to which all these operations are applied:
my_list = [1, 2, 3, 4]
print(my_list[0:3]) # [1, 2, 3]
print(my_list + my_list) # [1, 2, 3, 4, 1, 2, 3, 4]
print(my_list * 2) # [1, 2, 3, 4, 1, 2, 3, 4]
print(1 in my_list) # True
print([1, 2, 3, 4] == my_list) # True
Similarly, the same operations can be applied to a string as well:
str = "foobar"
print(str[0:3]) # 'foo'
print(str + str) # 'foobarfoobar'
print(str * 2) # 'foobarfoobar'
print('foo' in str) # True
print('foobar' == str) # True
In the following example you can see how the same operations can be applied to bytes:
bt = bytes([0, 1, 2, 3])
print(bt[0:3]) # b'\x00\x01\x02'
print(bt + bt) # b'\x00\x01\x02\x03\x00\x01\x02\x03'
print(bt * 2) # b'\x00\x01\x02\x03\x00\x01\x02\x03'
print(b'\x00' in bt) # True
print(b'\x00\x01\x02\x03' == bt) # True
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.