Python Sequence Types



In Python programming, some basic sequence type classes are, Lists , Strings , Tuples, Range, etc, these data structures hold an ordered collection of items. They allow us to access their elements through indexing and iteration, there are additional sequence-type objects such as Byte sequences.

Sequence Types In Python

Sequence types in Python are categorized into two types they are mutable and immutable sequences.

Mutable Sequence Types

These Sequences can be changed after their creation, and also we can modify elements, adding new elements and removing existing ones.

  • Lists: A list is a mutable, ordered collection of items.
  • Byte Arrays: A mutable sequence of bytes, used for handling binary data.

  • Arrays: A collection of items, similar to a list, but optimized for numeric operations and storing elements of the same data type.

Example

import array

# 1.List example
# creating list
my_list = [10, 20, 30, 40, 50]

# Appending element
my_list.append(60)
print(my_list)

# Removing element
my_list.remove(10)
print(my_list)

# 2.Byte Array example
# Creating byte array
my_byte_array = bytearray([15, 16, 17, 18])

# Modifying a byte
my_byte_array[1] = 19
print(my_byte_array)

# Removing a byte
my_byte_array.pop(3)
print(my_byte_array) 

# 3.Array example
# Creating array of integers
my_array = array.array('i', [21, 22, 23, 24, 25])

# Modifying element
my_array[2] = 26
print(my_array)

my_array.append(26)
print(my_array)

Output

[10, 20, 30, 40, 50, 60]
[20, 30, 40, 50, 60]
bytearray(b'\x0f\x13\x11\x12')
bytearray(b'\x0f\x13\x11')
array('i', [21, 22, 26, 24, 25])
array('i', [21, 22, 26, 24, 25, 26])

Immutable Sequence Types

Sequences classified as immutable have elements that are unchangeable once they are produced. Some immutable Sequence types are as follows.

  • Tuples: Tuples are known as collections of objects that are ordered and immutable.
  • Strings: Collection of Character sequences separated by single quotes ('') or double quotes ("") are referred to as strings.
  • Integers: Integers are defined as Whole numbers, both positive and negative, and are represented as integers, an immutable data type.

Example

# 1.Tuple example
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)

# Accessing element
print(my_tuple[3])

# Tuples Concatenation to create a new tuple
new_tuple = my_tuple + (60, 70)
print("New Tuple:", new_tuple)

# 2.String Example
# Creating a string
my_string = "Tutorials Point"

# Accessing a character
print(my_string[4])

# Strings can be concatenated to create a new string
new_string = my_string + " python"
print("String:", new_string)

# 3.Integer Example
# Creating an integer
my_integer = 30

# Performing operation to create new integer
new_integer = my_integer + 5
print("New Integer:", new_integer)
40
New Tuple: (10, 20, 30, 40, 50, 60, 70)
r
String: Tutorials Point python
New Integer: 35

Membership Operators

In Python, Membership Operators(in, not in) are used to check if a sequence is presented in an object.

Some common bulit-in methods and operations for the sequence type object that can work on both (mutable and immutable) sequences are as follows:

Operation Syntax Description
in x in seq Returns True, when x is found in the sequence seq, otherwise False
not in x not in seq Returns False, when x is found in the sequence seq, otherwise True

Example

lang = ['java', 'python', 'c++']
print('python' in lang) 
print('java' not in lang) 

Output

True
False

Concatenation and Repetition

Concatenations and Repetitions in Python are supported by sequence data types both mutable(list) and immutable(tuple, strings), but sequence types like range objects do not support these concatenation and repetition operations.

Operation Syntax Description
Concatenation sequence1 + sequence2 Concatenates(Combines) two sequences together
Repetition sequence * n Repeats the original sequence up to the given number of times(n)

Example

list1 = [10, 20, 30]
list2 = [40, 50]

#Concatenation (+)
print(list1 + list2)  

#Repetition (*)
print(list1 * 3)  

Output

[10, 20, 30, 40, 50]
[10, 20, 30, 10, 20, 30, 10, 20, 30]

Indexing and Slicing

Indexing is known as the process of accessing an element present in sequence by using its index. The first element's index in a Python sequence is 0, while the second element's index or position is 1.

Accessing a sub-sequence of a sequence by its starting and ending index (start, stop, and step values)is known as Slicing.

Operation Syntax Description
Indexing sequence[index] Access elements in a sequence by their position
Slicing sequence[start : stop : step] Access the sub-sequence of a sequence by start, stop, and step values.

Example

my_list = ['a', 'b', 'c', 'd','e']

#indexing
print(my_list[2])  

#slicing (start, stop)
print(my_list[1:4])

#(start,stop,step)
#Slices the sequence from index i to j with a step k.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[1:8:2])

Output

c
['b', 'c', 'd']
[1, 3, 5, 7]

Length, Search, and Count

We can determine the length of a sequence by using the built-in len() function. it can be applied to various types of sequences, such as strings, lists, tuples, etc.

Searching for a particular element in a sequence can done, depending on the type of sequence(lists, strings, tuples).

python's count() function, allows us to count the occurrences of elements that appear in a sequence.

Operation Syntax Description
Length len(sequence) Determine the number of elements in a sequence.
Search sequence.index(item) Finds the first occurrence of an element in a sequence..
Count sequence.count(item) Counts the number of times an element appears in a sequence.

Example

my_list = [1, 5, 4, 5, 3, 20, 12, 5, 43]

#Finding Length
print('length of sequence :',len(my_list))

#Searching an element
print('Element 12 at index :',my_list.index(12))

#counting the occurrences of an element
print('Num of times element 5 occurred :',my_list.count(5))

Output

length of sequence : 9
Element 12 at index: 6
Num of times element 5 occurred: 3

Append, pop, remove

In Python append, pop, and remove functions are commonly used with mutable sequence types like array, list, and bytearray.

  • append() method will add an element at the end of the existing list.

  • pop() method removes and returns the element at the required position in the list.

  • remove() method will remove the first occurrence of an element in the sequence.

These operations are not supported by immutable sequence types, such as tuples, strings, and integers, as they cannot be changed after creation.

Operation Syntax Description
append list.append(element) Add a single element at the end of the list
pop element = list.pop([index]) Removes and returns the element in sequence
remove list.remove(value) Deletes the first occurrence of an element in the sequence.

Example

my_list = [10, 20, 30, 40, 50]

#append element
my_list.append(60)
print(my_list)

#popping element
my_list.pop(1)
print(my_list)

#remove element
my_list.remove(40)
print(my_list) 

Output

[10, 20, 30, 40, 50, 60]
[10, 30, 40, 50, 60]
[10, 30, 50, 60]
Updated on: 2024-12-18T19:22:23+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements