Python – Sequence Types – Common Operations

Python supports variety of operations to work with Sequence Types. Almost all Sequence Types supports the common operations which we can apply on any of the Sequence Types what we have discussed in our Previous Articles.

In this Article, I am going to explain some of the Common Operations Python supports for Sequence Types.

in and not in Operations

Python provides in operation, to identify whether an items exists in the Sequence type. Conversely, not in operation works to identify whether the item in NOT in the Sequence type. Below are some example explains the usage of these operations:

>>> s = "Hello, World!"
>>> "e" in s
>>> "Hello" in s
>>> "hello" in s
>>> "Welcome" in s
>>> "Welcome" not in s

Concatenation (+) Operation

This operation combines one sequence type with another sequence type. Remember that, you can apply the concatenation operation ONLY on same sequence types. That means, you can combine one list with another list; but you can not combine the list with a string. Below are the examples shows how this operation works.

>>> l1 = [1, 2, 3]
>>> l2 = ["x", "y", "z"]
>>> l1 + l2
[1, 2, 3, 'x', 'y', 'z']

If you attempt to combine one type of sequence with another type of sequence, Python will throw the TypeError.

>>> l1 + s
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate list (not "str") to list

Find the length of the Sequence Type

len is the operation we use on all the sequence types to find the length of the sequence type OR number of items in the sequence type. For example, below statements finds the number of items in the list and the string sequence types.

>>> len(l1)
>>> len(s)

Identify the Smallest and Largest item in the Sequence Type

min and max operations are used to identify the smallest and largest item in the given Sequence type. Below examples explains this.

>>> min(l1)
>>> max(l1)

We discuss more on Python through upcoming Articles.


Python – Sequence Types – Common Operations

Leave a Reply

Your email address will not be published.

Scroll to top