Python Sequence and Collections – Operations, Functions, Methods

Keeping you updated with latest technology trends, Join DataFlair on Telegram

1. Python Sequence Tutorial

This blog is dedicated to a revision of the Python sequence and collections. In this Python Sequence Tutorial, we will discuss 6 types of Sequence: String, list, tuples, Byte sequences, byte array, and range object. Moreover, we will discuss Python sequence operations, functions, and methods. At last, we will cover python collection: sets and dictionaries.

So, let’s start Python Sequence and Collections

Python Sequence and Collections - Operations, Functions, Methods

Python Sequence and Collections – Operations, Functions, Methods

2. Python Sequence

So, what is a Python sequence, and how does it differ from a Python collection? A sequence is a group of items with a deterministic ordering. The order in which we put them in is the order in which we get an item out from them.

Python offers six types of sequences. Let’s discuss them.

a. Python Strings

A string is a group of characters. Since Python has no provision for arrays, we simply use strings. This is how we declare a string:

Python Sequence or Collection

We can use a pair of single or double quotes. And like we’ve always said, Python is dynamically-typed. Every string object is of the type ‘str’.

>>> type(name)

<class ‘str’>

To declare an empty string, we may use the function str():

>>> name=str()
>>> name

>>> name=str('Ayushi')
>>> name


>>> name[3]

To learn about strings in detail, read our chapter on Python Strings.

b. Python Lists

Since Python does not have arrays, it has lists. A list is an ordered group of items. To declare it, we use square brackets.

>>> groceries=['milk','bread','eggs']
>>> groceries[1]


>>> groceries[:2]

[‘milk’, ‘bread’]
A Python list can hold all kinds of items; this is what makes it heterogenous.

>>> mylist=[1,'2',3.0,False]

Also, a list is mutable. This means we can change a value.

>>> groceries[0]='cheese'
>>> groceries

[‘cheese’, ‘bread’, ‘eggs’]
A list may also contain functions.

>>> groceries[0]='cheese'
>>> groceries


>>> newlist=[sayhi,sayhi]
>>> newlist[0]

<function sayhi at 0x05907300>

>>> newlist[0]()

To learn more about lists, read up on Python Lists.

c. Python Tuples

A tuple, in effect, is an immutable group of items. When we say immutable, we mean we cannot change a single value once we declare it.

>>> name=('Ayushi','Sharma')
>>> type(name)

<class ‘tuple’>
We can also use the function tuple().

>>> name=tuple(['Ayushi','Sharma'])
>>> name

(‘Ayushi’, ‘Sharma’)
Like we said, a tuple is immutable. Let’s try changing a value.

>>> name[0]='Avery'

Traceback (most recent call last):

File “<pyshell#594>”, line 1, in <module>


TypeError: ‘tuple’ object does not support item assignment

To learn more about tuples, read Tuples in Python.

Also read up on Python namedtuple.

d. Bytes Sequences

The function bytes() returns an immutable bytes object. We dealt with this when we talked Built-in Functions in Python. Let’s take a few examples.

>>> bytes(5)


>>> bytes([1,2,3,4,5])


>>> bytes('hello','utf-8')

b ‘hello’

Here, utf-8 is the encoding we used.

Since it is immutable, if we try to change an item, it will raise a TypeError.

>>> a=bytes([1,2,3,4,5])
>>> a


>>> a[4]=3

Traceback (most recent call last):

File “<pyshell#46>”, line 1, in <module>


TypeError: ‘bytes’ object does not support item assignment

e. Bytes Arrays

In that article, we discussed this one too. A bytesarray object is like a bytes object, but it is mutable. It returns an array of the given byte size.

>>> a=bytearray(4)
>>> a


>>> a=bytearray(4)
>>> a


>>> a[0]=1
>>> a


>>> a[0]

Let’s try doing this on a list.

>>> bytearray([1,2,3,4])


Finally, let’s try changing a value.

>>> a=bytearray([1,2,3,4,5])
>>> a


>>> a[4]=3
>>> a


See? It is mutable.

f. range() objects

A range() object lends us a range to iterate on; it gives us a list of numbers.

>>> a=range(4)
>>> type(a)

<class ‘range’>

>>> for i in range(7,0,-1):

We took an entire post on Range in Python.

3. Python Sequence Operations

Since we classify into sequences and collections, we might as well discuss the operations we can perform on them. For simplicity, we will demonstrate these on strings.

  1. Concatenation

Concatenation adds the second operand after the first one.

>>> 'Ayu'+'shi'


  1. Integer Multiplication

We can make a string print twice by multiplying it by 2.

>>> 'ba'+'na'*2


  1. Membership

To check if a value is a member of a sequence, we use the ‘in’ operator.

>>> 'men' in 'Disappointment'

You can read more about these operations in Python Operators.

  1. Python Slice

Sometimes, we only want a part of a sequence, and not all of it. We do it with the slicing operator.

>>> 'Ayushi'[1:4]


4. Python Sequence Functions

  1. len()

A very common and useful function to pass a sequence to is len(). It returns the length of the Python sequence.

>>> len('Ayushi')


  1. min() and max()

min() and max() return the lowest and highest values, respectively, in a Python sequence.

>>> min('cat')


>>> max('cat')

This comparison is based on ASCII values.

5. Python Sequence Methods

There are some methods that we can call on a Python sequence:

  1. Python index()

This method returns the index of the first occurrence of a value.

>>> 'banana'.index('n')


  1. Python count()

count() returns the number of occurrences of a value in a Python sequence.

>>> 'banana'.count('na')


>>> 'banana'.count('a')


6. Python Collections

Python collection, unlike a sequence, does not have a deterministic ordering. Examples include sets and dictionaries. In a collection, while ordering is arbitrary, physically, they do have an order.

Every time we visit a set, we get its items in the same order. However, if we add or remove an item, it may affect the order.

a. Python Set

A set, in Python, is like a mathematical set in Python. It does not hold duplicates. We can declare a set in two ways:

>>> nums={2,1,3,2}
>>> nums

{1, 2, 3}

>>> nums=set([1,3,2])
>>> nums

{1, 2, 3}
A set is mutable.

>>> nums.discard(2)
>>> nums

{1, 3}
But it may not contain mutable items like lists, dictionaries, or other sets.

To learn more about sets, read up on Python Sets and Booleans.

Any doubt in Python Sequences and Collections yet? Please Comment.

b. Python Dictionaries

Think of a dictionary as a real-life dictionary. It holds key-value pairs, and this is how we declare it:

>>> a={'name':1,'dob':2}

Or, you could do:

>>> a=dict()
>>> a['name']=1
>>> a['dob']=2
>>> a

{‘name’: 1, ‘dob’: 2}
We have yet another way to create a dictionary- a dictionary comprehension.

>>> a={i:2**i for i in range(4)}
>>> a

{0: 1, 1: 2, 2: 4, 3: 8}
However, a key cannot be of an unhashable type.

>>> a={[1,2,3]:1,1:[1,2,3]}

Traceback (most recent call last):

File “<pyshell#629>”, line 1, in <module>


TypeError: unhashable type: ‘list’

To know more about dictionaries, read up on Python Dictionaries. You should also check out defaultdict and OrderedDict in Python.

So, this was all about the Python sequence and collections tutorial. Hope you like our explanation.

4. Conclusion

To conclude this Python Sequence and collection tutorial, we will say that a sequence has a deterministic ordering, but a collection does not. Examples of sequences include strings, lists, tuples, bytes sequences, bytes arrays, and range objects. Those of collections include sets and dictionaries.
If you have any query regarding Python Sequence and Collection Tutorial, Please Comment.

For reference

4 Responses

  1. Anumula Sandeep Reddy says:

    Hi ,
    please check this line {0: 1, 1: 2, 2: 4, 3: 8} in dictionary topic.
    it should be {0: 1, 1: 2, 2: 4, 3: 8}

    • DataFlair Team says:

      Hi Anumula
      Thanks for reading the Python Sequence tutorial. We didn’t get your point. You have written the same thing which you mention as an error.
      Still, we have checked this there is no need to do changes.
      We request you to check again and tell us your query.
      DataFlair Team.

  2. Jatin says:

    What is unhashable?
    Do all mutable values are unhashable type?

    • DataFlair Team says:

      You can think of a hash as a unique value for each input. All the mutable objects are unhashable, Example of mutable/unhashable are list, sets, and dictionary. Since mutable objects can change their value therefore they cannot be hashed. So yes, all mutable values are unhashable.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.