Sequences in Python with Types and Examples

Master programming with our job-ready courses: Enroll Now

When it comes to ease of writing code, Python is the most preferred language due to its large community, extensive library support, and data structures.

One such category of python data structures is Sequence. Let us see what is a sequence in Python? Will also see operations that can be performed on these sequences.

Sequences in Python

Sequences are containers with items stored in a deterministic ordering. Each sequence data type comes with its unique capabilities.

There are many types of sequences in Python. Let’s learn them with Examples.

Types of Sequences in Python

Python sequences are of six types, namely:

  1. Strings
  2. Lists
  3. Tuples
  4. Bytes Sequences
  5. Bytes Arrays
  6. range() objects

Let’s discuss them one by one.

Strings in Python

In python, the string is a sequence of Unicode characters written inside a single or double-quote. Python does not have any char type as in other languages (C, C++), therefore, a single character inside the quotes will be of type str only.

1. To declare an empty string, use str() or it can be defined using empty string inside quotes.

Example of Empty String in Python

name = "PythonGeeks"
print(name)

Output

PythonGeeks

2. Strings are immutable data types, therefore once declared, we can’t alter the string. Though, we can reassign it to a new string.

Code

name = "PythonGeeks"
print(name[6]) # outputs 'G'
name[6] = 'g' # throws error
print(name)

Output

G

Traceback (most recent call last):

  File “/home/apoorve/Documents/PythonGeeks/python_sequences/main.py”, line 3, in <module>

    name[7] = ‘g’

TypeError: ‘str’ object does not support item assignment

Lists in Python

Lists are a single storage unit to store multiple data items together. It’s a mutable data structure, therefore, once declared, it can still be altered.

A list can hold strings, numbers, lists, tuples, dictionaries, etc. 

1. To declare a list, either use list() or square brackets [], containing comma-separated values.

Example of Lists in Python

list_1 = ["PythonGeeks", "Sequences", "Tutorial"] # [all string list]
print(f'List 1: {list_1}')

list_2 = list() # [empty list]
print(f'List 2: {list_2}')

list_3 = [2021, ['hello', 2020], 2.0] # [integer, list, float]
print(f'List 3: {list_3}')

list_4 = [{'language': 'Python'}, (1,2)] # [dictionary, tuple]
print(f'List 4: {list_4}')

Output

List 1: [‘PythonGeeks’, ‘Sequences’, ‘Tutorial’]
List 2: []
List 3: [2021, [‘hello’, 2020], 2.0]
List 4: [{‘language’: ‘Python’}, (1, 2)]

2. Let’s check the mutability of lists, now.

Code

list_1 = ["PythonGeeks", "Sequences", "Tutorial"] # [all string list]
list_1[2] = "Blog"
print(list_1)

Output

[‘PythonGeeks’, ‘Sequences’, ‘Blog’]

Tuples in Python

Just like Lists, Tuples can store multiple data items of different data types. The only difference is that they are immutable and are stored inside the parenthesis ().

1. To declare a tuple, either use tuple() or parenthesis, containing comma-separated values.

Example of Tuple in Python:

tuple_1 = ("PythonGeeks", "Sequences", "Tutorial") # [all string tuple]
print(f'tuple 1: {tuple_1}')

tuple_2 = tuple() # [empty tuple]
print(f'tuple 2: {tuple_2}')

tuple_3 = [2021, ('hello', 2020), 2.0] # [integer, tuple, float]
print(f'tuple 3: {tuple_3}')

tuple_4 = [{'language': 'Python'}, [1,2]] # [dictionary, list]
print(f'tuple 4: {tuple_4}')

Output:

tuple 1: (‘PythonGeeks’, ‘Sequences’, ‘Tutorial’)
tuple 2: ()
tuple 3: [2021, (‘hello’, 2020), 2.0]
tuple 4: [{‘language’: ‘Python’}, [1, 2]]

2. Let’s test the immutability of tuples now.

Code:

tuple_1 = ("PythonGeeks", "Sequences", "Tutorial") # [all string tuple]
tuple_1[2] = "Blog"
print(tuple_1)

Output:

Traceback (most recent call last):
File “/home/apoorve/Documents/PythonGeeks/python_sequences/main.py”, line 2, in <module>
tuple_1[3] = “Blog”
TypeError: ‘tuple’ object does not support item assignment

Byte Sequences in Python

The bytes() function returns an immutable bytes sequence in between quotes, preceded by a ‘B’ or ‘b’.

1. To declare an empty bytes object, use bytes(size), where size is the number of empty bytes we want to generate.

Example of Byte Sequences in Python:

size = 10
b = bytes(size)
print(b)

Output:

b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′

2. Alternatively, we can pass a list of numbers in bytes() function as follows:

Code:

b = bytes([5,8])
print(b)

Output:

B’\x05\x08’

3. In the case of strings, we need to pass a second parameter as the type of encoding.

Code:

b = bytes("PythonGeeks", 'utf-8')
print(b)

Output:

b’PythonGeeks’

Byte Arrays in Python

Just like bytes sequence, bytes arrays also return a bytes object. The only difference is that they are mutable

1. Let’s see how to use them.

Example of Byte Arrays in Python:

print(bytearray(10))
print(bytearray([5,8]))
print(bytearray("PythonGeeks", 'utf-8'))

Output:

bytearray(b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′)
bytearray(b’\x05\x08′)
bytearray(b’PythonGeeks’)

2. Try mutating a byte in the array.

Code:

b = bytearray([10,20,60,40,50])
print(f'Before: {b}')
b[2] = 30
print(f'Later: {b}')

Output:

Before: bytearray(b’\n\x14<(2′)
Later: bytearray(b’\n\x14\x1e(2′)

range() object in Python

It returns a sequence of integers in the specified range. By default, it starts the sequence from 0 (if not specified). 

Code:

sequence = range(10)
print(sequence)

Output:

range(0,10)

Code:

for i in range(2,5):
   print(i)

Output:

2
3
4

As a third parameter, we can specify the increment count (here, 2). By default it is set to 1.

Code:

sequence= range(1, 10, 2)
for i in sequence:
   print(i)

Output:

1
3
5
7
9

Operations on Sequences in Python

We now know the types of sequences, but now, it’s time to see what all operations can we perform on them. Here, we will focus on the most commonly used operations.

1. Concatenation Operator in Python

(+) operator is used to join two sequences of the same type.

Code:

print(["Python"] + ["Geeks"])

Output:

[“Python”, “Geeks”]

2. Repeat Operator in Python

(*) operator repeats a sequence specified number of times.

Code:

print(("PythonGeeks", 1) * 2)

Output:

(‘PythonGeeks’, 1, ‘PythonGeeks’, 1)

3. Membership Operator in Python

These are used to check whether a value is present in a sequence or not using the “in” and “not in” operators.

Code:

dict = {
   "lang" : "Python",
   "platform": "PythonGeeks"
}
print("lang" in dict)
print("code" not in dict)

Output:

True
True

4. Slicing Operator in Python

[:] operator returns a part of the sequence between a given range.

Code:

list_1 = [3,2,5,6,7]
print(list_1[:5])
print(list_1[2:4])
print(list_1[-1:])

Output:

[3, 2, 5, 6, 7]
[5, 6]
[7]

Python Sequence Functions and Methods

Now, it’s time to discuss some important functions and methods used for sequences of all the types.

1. len(sequence) : Returns length of a sequence.

2. index(index): Returns index of the first occurrence of an element in a sequence.

3. min(sequence): Returns the minimum value of a sequence.

4. max(sequence): Returns maximum value of a sequence.

5. count(): Returns the count of a number of occurrences of an element in a sequence.

6. append(value): Adds the value at the end of the sequence.

7. clear(): Clears all the contents of the sequence.

8. insert(value, index): Inserts the value at the index “index” of the sequence.

9. pop(index): Returns and deletes elements at index “index”. By default, the last element is deleted from the sequence.

10. remove(value): Removes the first occurrence of value from the sequence.

11. reverse(): Reverse the sequence

Example of Sequence Function in Python

test = [2, 4, 6, 8, 10, 10]

print(len(test))

print(test.index(6))

print(min(test))

print(max(test))

print(test.count(10))

test.append(11)
print(test)

test.clear()
print(test)

test = [2, 4, 6, 8, 10, 10]
test.insert(9,4)
print(test)

print(test.pop())

test.remove(10)
print(test)

test.reverse()
print(test)

Output:

6
2
2
10
2
[2, 4, 6, 8, 10, 10, 11]
[]
[2, 4, 6, 8, 10, 10, 4]
4
[2, 4, 6, 8, 10]
[10, 8, 6, 4, 2]

Interview Questions on Sequences in Python

To make you understand some more important concepts of Python Sequences, we have curated a list of Top 5 Question and Answers that will help you hit the pot of gold in your upcoming interviews:

Q1. What will be the output of the code below?

b  = range(0,10)
print(type(b))

Ans 1.

>>> <class ‘range’>

Though printing b will return a list of numbers from 0 to 10, that doesn’t mean it is of type list. range() object is of type range.

Q2. Is it possible to write a for loop to create a list from space-separated input in one line? If yes, then how?

Ans 2. Yes, it is possible to write a one-liner code for creating a list or performing any other operation on list elements. This is how we can do that.

list_1 = [i for i in input("Input: ").split()] # input 2 5 8 10
print(list_1)

Here, input().split() will take space-separated input for list elements and append them to the list list_1.

Output:

Input: 2 5 8 10
[‘2’, ‘5’, ‘8’, ’10’]

Q3. id() function in python, accepts a single parameter and is used to return the identity of an object. In simple words, objects pointing to the same memory address have the same id and vice-a-versa.

Based on this, tell whether the id for list1 and list2 will be the same or different?

list1= ["PythonGeeks"]
list2 = list1

Ans 3. The id for both lists will be the same. This is because, list2 = list1 doesn’t mean that we are creating a copy of list1 in a different memory block, but it means that we are creating another list that points to the same memory location.

Therefore, they have the same id, and any change made in list2 will be reflected on list1 and vice-a-versa.

Q4. Write code to convert the following tuple of the list to a simple tuple.
Example: ([1,2],[5,6,7]) => (1,2,5,6,7)

Ans 4. Code is as follows:

tuple_before = ([2,3,4], [8,9],[20])

# Combination of sum() and tuple() function
tuple_after = tuple(sum(tuple_before, []))

print(tuple_after)

Output:

(2,3,4,8,9,20)

This is because the sum() function adds an empty list to each element of the tuple to create a list of the same numbers as in the input tuple. Then the list is converted into tuple using the tuple() function.

Q5. How to partition a string at a particular word, into a tuple of substrings?

Ans 5. Suppose our string is “PythonGeeks is the best platform for self-paced learning of Python”.
Now if we want to split it at the word “ best “ into a tuple of substrings, here is how we do it using Python’s built-in string method partition()

Code:

 string = "PythonGeeks is the best platform for self-paced learning of Python"
print(string.partition(" best "))

Output:

(‘PythonGeeks is the’, ‘ best ‘, ‘platform for self-paced learning of Python’)

Quiz on Sequences in Python

Conclusion

In this tutorial, we learned what are Python Sequences and different types of sequences: strings, lists, tuples, byte sequence, byte arrays, and range() objects.

We also saw what different operations we can perform on any sequence, and how some functions make it even easier to iterate through these sequences.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


PythonGeeks Team

At PythonGeeks, our team provides comprehensive guides on Python programming, AI, Data Science, and machine learning. We are passionate about simplifying Python for coders of all levels, offering career-focused resources.

2 Responses

  1. Harsh Taliwal says:

    Very informative. Learnt a lot!!

  2. Yogesh Kamboj says:

    Topics presented nicely.

Leave a Reply

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