Python Sequences – Types, Operations, and Functions
Today, we are going to revise the different Python data structures. They can be divided into two categories based on the ordering of items: Sequences and Collections. Elements in sequences come out in the same order as it is inserted, however ordering in collections is not preserved. In this article, we will focus only on sequences.
So, let’s get started.
In Python programming, sequences are a generic term for an ordered set which means that the order in which we input the items will be the same when we access them. Python supports six different types of sequences. These are strings, lists, tuples, byte sequences, byte arrays, and range objects. We will discuss each of them.
Types of Python Sequences
Strings are a group of characters written inside a single or double-quotes. Python does not have a character type so a single character inside quotes is also considered as a string.
name = “TechVidvan” type(name)
Strings are immutable in nature so we can reassign a variable to a new string but we can’t make any changes in the string.
city= ‘China’ print(city) city = ‘a’
File “<stdin>”, line 3, in <module>
TypeError: ‘str’ object does not support item assignment
Learn more about strings in TechVidvan’s Python strings article.
Python lists are similar to an array but they allow us to create a heterogeneous collection of items inside a list. A list can contain numbers, strings, lists, tuples, dictionaries, objects, etc. Lists are declared by using square brackets around comma-separated items.
list1 = [1,2,3,4] list2 = [‘red’, ‘green’, ‘blue’] list3 = [‘hello’, 100, 3.14, [1,2,3] ]
Lists are mutable which makes it easier to change and we can quickly modify a list by directly accessing it.
list = [10,20,30,40] list = 100 print( list)
Time to have an in-depth knowledge of the Python lists with TechVidvan.
Tuples are also a sequence of Python objects. A tuple is created by separating items with a comma. They can be optionally put inside the parenthesis () but it is necessary to put parenthesis in an empty tuple. A single item tuple should use a comma in the end.
tup = () print( type(tup) ) tup = (1,2,3,4,5) tup = ( “78 Street”, 3.8, 9826 ) print(tup)
(’78 Street’, 3.8, 9826)
Tuples are also immutable like strings so we can only reassign the variable but we cannot change, add or remove elements from the tuple.
tup = (1,2,3,4,5) tup = 10
File “<stdin>”, line 2, in <module>
TypeError: ‘tuple’ object does not support item assignment
Dig in TechVidvan’s Python tuples article to have a detailed insight on tuples.
Bytes Sequences in Python
The bytes() function in Python is used to return an immutable bytes sequence. Since they are immutable, we cannot modify them. If you want a mutable byte sequence, then it is better to use byte arrays.
This is how we can create a byte of a given integer size.
size = 10 b = bytes(size) print( b )
Iterables can be converted into bytes.
print( bytes([4,2,1]) )
For strings, we have to provide the encoding in the second parameter.
Byte Arrays in Python
Byte arrays are similar to bytes sequence. The only difference here is that byte arrays are mutable while bytes sequences are immutable.
So, it also returns the bytes object the same way.
print( bytearray(4) ) print( bytearray([1, 2, 3, 4]) ) print( bytearray(‘Hola!’, ‘utf-8’))
Since byte arrays are mutable, let’s try changing a byte from the array.
a = bytearray([1,3,4,5]) print(a) a = 2 print(a)
Python range() objects
range() is a built-in function in Python that returns us a range object. The range object is nothing but a sequence of integers. It generates the integers within the specified start and stop range. Let’s see this with an example.
num = range(10) print( type(num) )
Since range object generates integers, we can access them by iterating using a for loop.
for i in range(5): print(i)
The first argument is the starting range, the second argument is the stopping range and the third argument tells how many steps to take.
for i in range(4,16,2): print()
Any doubts in TechVidvan’s Python sequences article till now? Mention them in the comment section.
Let’s discuss the operations we can perform on the sequences.
The operator (+) is used to concatenate the second element to the first. For example – [1,3,4] + [1,1,1] will evaluate to [1,3,4,1,1,1]. We can concate all other sequences like this.
The operator (*) is used to repeat a sequence n number of times. For example – (1,2,3) * 3 will evaluate to (1,2,3,1,2,3,1,2,3). This also works on sequences other than tuples.
3. Membership Operators
Membership operators (in) and (not in) are used to check whether an item is present in the sequence or not. They return True or False. For example – ‘la’ in “Manilla” evaluates to True and ‘a’ not in ‘all’ evaluates to False.
4. Slicing Operator
All the sequences in Python can be sliced. The slicing operator can take out a part of a sequence from the sequence. For example –
print( "The new york times"[4:10] ) print( (1,2,3,4,5)[1:3] )
Check out TechVidvan’s Python operators to ease your programming.
Let us discuss some of the useful functions we can use on sequences.
The len() function is very handy when you want to know the length of the sequence.
len(“This is a sentence”)
2. min() and max()
The min() and max() functions are used to get the minimum value and the maximum value from the sequences respectively.
The index() method searches an element in the sequence and returns the index of the first occurrence.
The count() method counts the number of times an element has occurred in the sequence.
In this article, we have seen the Python sequences. We learned about the six different types of sequences: strings, lists, tuples, byte sequences, byte arrays, and range objects. We saw examples of each sequence on how to create them, then learned about the operations and functions associated with them.
If you liked our article and want an article on any specific topic of Python, do let us know in the comment section.