In this part of the Python Basics tutorial, we will learn about the sequence in python. First, we will have to understand what sequences are.
What are sequences in python?
Sequences are kind of objects which are used to store a series (or sequence, or a group) of data of any data type and are usually meant to be iterated.
They have deterministic ordering. This means that the order in which we get items out of the sequence is exactly the same as the order in which they were inserted into the sequence.
Types of sequences in python
The mostly used types of sequences in python are listed below.
Lists and Tuples can store data of any data type. On the other hand, Strings can only store a series of characters (which is quite obvious by the name ;P).
Now, let’s try to get a basic idea of each type of sequence mentioned above.
To declare a list in python, we use square brackets. A list is an ordered group of items.
A list is mutable. When we say mutable, we mean that we can change the value of an item even after it is inserted in it.
Let’s look at some basic operations on list below.
>>> l = [1,2,3,'apple',5,6] >>> print(l) [1, 2, 3, 'apple', 5, 6]
Indexing in a list
We can use the index number to get the data of a list store at a specific index.
>>> l 3 >>> l[-1] 6
Appending in a list
We use the .append() method to add items to the given list.
>>> l.append(7) >>> l [1, 2, 3, 'apple', 5, 6, 7]
Slicing in a list
Slicing a list helps us in breaking a given list into a smaller list. Look at the example below.
>>> l[2:-1] [3, 'apple', 5, 6] >>>
Reassignment of list item
We already know that list is mutable i.e. we can change the value of an item already present in the list. Let’s see how that works.
>>> l = 'three' >>> l [1, 2, 'three', 'apple', 5, 6, 7] >>>
To declare a tuple in python, we use parenthesis. Like lists, a tuple is also an ordered group of items.
A tuple is an immutable group of items. When we say immutable, we mean we cannot change a single value once we declare it.
Let’s have a look on some basic operations on tuple below.
>>> t = (1,2,3,'apple',5,6) >>> print(t) (1, 2, 3, 'apple', 5, 6) >>> t 3 >>> t[-1] 6 >>> t[2:-1] [3, 'apple', 5, 6] >>>
As we already discussed, a tuple is immutable. Let’s see what happens when we try to change the value of an item present in the tuple.
>>> t = 'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>>
This throws an error as expected 🙂
A string is a sequence or a group of characters.
Let’s have a look on some basic string operations below.
>>> string = 'MostlyPy' >>> string 'MostlyPy' >>> string 'M' >>> string[-1] 'y' >>> string[0:-2] 'Mostly' >>>