Skip to main content
  1. Blog posts/

Python - Sequence types

·3 mins

This article explains sequence types in Python, which are data types where values are connected continuously.

What are Sequence Types? #

Sequence types refer to data types where values are connected in a sequence.

The biggest feature of sequence types is that they provide common actions and functionalities.

List [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
Tuple (1, 2, 3, 4, 5) (1, 2, 3, 4, 5)
Range range(5) 0, 1, 2, 3, 4
String ‘Hello’ H e l l o

As shown above, sequence types include lists, tuples, ranges, and strings, and also (bytes, bytearray).

Objects created with sequence types are called sequence objects, and each value of the object is called an element.

Checking for a Specific Value in a Sequence Object #

To check whether a specific value exists within a sequence object, you can use in or not in as shown below.

>>> a = "Hello"
>>> "H" in a
True
>>> "A" in a
False
# not in checks if a specific value does not exist
>>> "ell" not in a
False
>>> "Python" not in a
True

Using the in operator, if a specific value exists, it returns True, otherwise False. Conversely, using the not in operator, if a specific value does not exist it returns True, otherwise False.

Connecting Sequence Objects #

Sequence objects can be connected using the + operator.

>>> a = [0, 1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b 
[0, 1, 2, 3, 4, 5, 6]

However, range cannot be connected using the + operator.

>>> range(0, 5) + range(5, 10)
TypeError Traceback (most recent call last)
<ipython-input-7-88e74efcb3c0> in <cell line: 1>()
----> 1 range(0, 5) + range(5, 10)
TypeError: unsupported operand type(s) for +: 'range' and 'range'

Therefore, converting range to tuples or lists for connection is possible.

>>> tuple(range(0, 5)) + tuple(range(5, 10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> list(range(0, 5)) + list(range(5, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Repeating Sequence Objects #

Sequence objects can be repeated using the * operator.

Repetition is possible with integer * sequence object or sequence * integer.

>>> [0, 1, 2, 3] * 3
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

However, similar to the method of connecting sequence objects, ranges cannot be repeated using the * operator.

>>> range(0,10) * 3
TypeError Traceback (most recent call last)
<ipython-input-11-824dcf3cff8f> in <cell line: 1>()
----> 1 range(0,10) * 3
TypeError: unsupported operand type(s) for *: 'range' and 'int'

Therefore, converting to tuples or lists for repetition is possible.

Checking the Number of Elements in a Sequence Object #

The number of elements in a sequence object can be checked using the len function.

# List
>>> a = [1, 2, 3, 4, 5]
>>> len(a)
5
# Tuple
>>> b = (6, 7, 8, 9, 10)
>>> len(b)
5
# Range
len(range(0, 5, 2)) # -> Increasing by 2 from 0 to 5 gives 0, 2, 4
3
# String
>>> c = "Hello, World"
>>> len(c)
12