0% found this document useful (0 votes)
2 views10 pages

SequenceData Operations

The document provides an overview of various sequence data types in Python, including strings, tuples, lists, arrays, dictionaries, sets, and ranges, along with their initialization and operations such as indexing, slicing, concatenation, and multiplication. It explains how to access elements using indexing and demonstrates various methods for manipulating these data types. Additionally, it highlights the unique functionalities and constraints associated with each data type.

Uploaded by

sugaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

SequenceData Operations

The document provides an overview of various sequence data types in Python, including strings, tuples, lists, arrays, dictionaries, sets, and ranges, along with their initialization and operations such as indexing, slicing, concatenation, and multiplication. It explains how to access elements using indexing and demonstrates various methods for manipulating these data types. Additionally, it highlights the unique functionalities and constraints associated with each data type.

Uploaded by

sugaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

* -- coding: utf-8 -- * *@author: GITAA *

Sequence data type


Strings - Sequence of characters - " (or) '
Tuples - Sequence of compound data - ()
Lists - Sequence of multi-data type objects - []
Arrays - Sequence of constrained list of objects (all objects of same datatype)

- using array module from array package

Dictionary- Sequence of key-value pairs - {}


Sets - Sequence of unordered collection of unique data
Range - Used for looping - using built-in range( )

These can offer unique functionalities for the variables to contain and handle more than one data datatype at a time
Supports operations such as indexing, slicing, concatenation, multiplication etc.,

Sequence object initialization

In [ ]: strSample = 'learning' # string

In [ ]: lstNumbers = [1, 2, 3, 3, 3, 4, 5] # list with numbers


# (having duplicate values)
print(lstNumbers)

In [ ]: lstSample = [1,2,'a','sam',2] # list with mixed data types


print(lstSample) # (Having numbers and strings)

/
In [ ]: from array import * # importing array module

arrSample = array('i',[1,2,3,4]) # array

for x in arrSample: print(x) # printing values of array

The data types mentioned below can be used in creating an array of different data types.
Code Python Type Min bytes
===============================
'b' int 1
'B' int 1
'u' Unicode 2
'h' int 2
'H' int 2
'i' int 2
'I' int 2
'l' int 4
'L' int 4
'f' float 4
'd' float 8

In [ ]: tupSample = (1,2,3,4,3,'py') # tuple

In [ ]: tupleSample = 1, 2, 'sample' # tuple packing


print(tupleSample)

In [ ]: dictSample = {1:'first', 'second':2, 3:3, 'four':'4'} # dictionary

In [ ]: # Creating dictionary using 'dict' keyword


dict_list = dict([('first', 1), ('second', 2), ('four', 4)])
dict_list

In [ ]: setSample = {'example',24,87.5,'data',24,'data'} # set


setSample

/
In [ ]: rangeSample= range(1,12,4) # built-in sequence type used for looping

print(rangeSample)

for x in rangeSample: print(x) # print the values of 'rangeSample'

Sequence data operations: Indexing

Indexing just means accessing elements. To access elements, the square brackets can be used. There are many methods to access elements in python.

index() method finds the first occurrence of the specified value and returns its position

Syntax: object.index(sub[, start[, end]] ), object[index]

Index of the element is used to access an element from ordered sequences


The index starts from 0
Negative indexing is used to access elements from the end of a list
In negative indexing, the last element of a list has the index -1

String: Indexing
In [2]: strSample = 'learning' # string

In [3]: strSample.index('l') # to find the index of substring 'l' from the string 'learning'

Out[3]: 0

In [4]: strSample.index('ning') # to find the index of substring 'ning' from the string 'learning'

Out[4]: 4

/
In [5]: strSample[7] # to find the substring corresponds to 8th position

Out[5]: 'g'

In [6]: strSample[-2] # to find the substring corresponds to 2nd last position

Out[6]: 'n'

In [8]: strSample[-9] # IndexError: string index out of range

Traceback (most recent call last):

File "<ipython-input-8-dd2637980702>", line 1, in <module>


strSample[-9] # IndexError: string index out of range

IndexError: string index out of range

List: Indexing

Syntax: list_name.index(element, start, end)


In [10]: lstSample = [1,2,'a','sam',2] # list

In [11]: lstSample.index('sam') # to find the index of element 'sam'

Out[11]: 3

In [12]: lstSample[2] # to find the element corresponds to 3rd position

Out[12]: 'a'

/
In [13]: lstSample[-1] # to find the last element in the list

Out[13]: 2

Array: Indexing
In [15]: from array import * # importing array module

In [16]: arrSample = array('i',[1,2,3,4])# array with integer type

In [17]: for x in arrSample: print(x) # printing the values of 'arrSample'

1
2
3
4

In [18]: arrSample[-3] # to find the 3rd last element from 'arrSample'

Out[18]: 2

Tuple: Indexing
In [20]: tupSample = (1,2,3,4,3,'py') # tuple

In [22]: tupSample.index('py') # to find the position of the element 'py'

Out[22]: 5

In [23]: tupSample[2] # to find the 3rd element of the 'tupSample'

Out[23]: 3

/
Set: Indexing
In [24]: setSample = {'example',24,87.5,'data',24,'data'} # sets

In [25]: setSample[4] # TypeError: 'set' object does not support indexing

Traceback (most recent call last):

File "<ipython-input-25-b907ea72430f>", line 1, in <module>


setSample[4] # TypeError: 'set' object does not support indexing

TypeError: 'set' object is not subscriptable

Dictionary: Indexing
The Python Dictionary object provides a key: value indexing facility
The values in the dictionary are indexed by keys, they are not held in any order

In [27]: dictSample = {1:'first', 'second':2, 3:3, 'four':'4'} # dictionary

In [28]: dictSample[2] # KeyError: 2 - indexing by values is not applicable in dictionary

Traceback (most recent call last):

File "<ipython-input-28-29139fb75065>", line 1, in <module>


dictSample[2] # KeyError: 2 - indexing by values is not applicable in dictionary

KeyError: 2

In [29]: dictSample[1] # to find the value corresponds to key 1

Out[29]: 'first'
/
In [30]: dictSample['second'] # to find the value corresponds to key second

Out[30]: 2

range: Indexing
In [31]: rangeSample= range(1,12,4) # built-in sequence type used for looping

for x in rangeSample: print(x) # print the values of 'rangeSample'

1
5
9

In [32]: rangeSample.index(0) # ValueError: 0 is not in range

Traceback (most recent call last):

File "<ipython-input-32-6e72d566a242>", line 1, in <module>


rangeSample.index(0) # ValueError: 0 is not in range

ValueError: 0 is not in range

In [33]: rangeSample.index(9) # to find index of element 1

Out[33]: 2

In [34]: rangeSample[1] # given the index, returns the element

Out[34]: 5

/
In [35]: rangeSample[9] # IndexError: range object index out of range

Traceback (most recent call last):

File "<ipython-input-35-d3bead8072c7>", line 1, in <module>


rangeSample[9] # IndexError: range object index out of range

IndexError: range object index out of range

=============================================================================

Sequence data operations: Slicing

The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step)
Syntax: slice(stop), slice(start, stop, step)
If a single parameter is passed, start and step are set to None

In [ ]: strSample[slice(4)] # getting substring 'lear' from 'learning'

In [ ]: strSample[slice(1,4,2)] # getting substring 'er'

In [ ]: strSample[:] # learning

In [ ]: lstSample[-3:-1] # ['a', 'sam']

In [ ]: dictSample[1:'second'] # TypeError: unhashable type: 'slice'

/
In [ ]: setSample[1:2] # TypeError: 'set' object is not subscriptable

In [ ]: arrSample[1:] # array('i', [2, 3, 4])

In [ ]: arrSample[1:-1] # array('i', [2, 3])

In [ ]: rangeSample[:-1] # range(1, 9, 4)

=============================================================================

Sequence data operations: Concatenation

Syntax: ',','+','+='

In [ ]: lstSample+['py'] # [1, 2, 'a', 'sam', 2, 'py']

In [ ]: print(strSample+' ','python') # learning python

In [ ]: arrSample+[50,60] # TypeError: can only append array (not "list") to array

In [ ]: arrSample+array('i',[50,60]) # array('i', [1, 2, 3, 4, 50, 60])

In [ ]: tupSample+=('th','on')
print(tupSample) # (1, 2, 3, 4, 3, 'py', 'th', 'on')

In [ ]: setSample=setSample,24 # Converts to tuple with comma separated elements of set, dict, range
print(setSample) # ({24, 'data', 'example', 87.5}, 24)

=============================================================================
/
Sequence data operations: Multiplication

Syntax: object*integer

In [ ]: lstSample*2 # [1, 2, 'a', 'sam', 2, 1, 2, 'a', 'sam', 2]

In [ ]: lstSample[1]*2 # 4

In [ ]: lstSample[2]*2 # aa

In [ ]: tupSample[2:4]*2 # (3, 4, 3, 4) : Concatenate sliced tuple twice

In [ ]: tupSample[1]/4 # 0.5

In [ ]: arrSample*2 # array('i', [1, 2, 3, 4, 1, 2, 3, 4])

In [ ]: strSample*=3 # concatenate thrice

In [ ]: print(strSample) # learninglearninglearning

In [ ]: rangeSample*2 # TypeError: unsupported operand type(s) for *: 'range' and 'int'

=============================================================================

END OF SCRIPT

You might also like