General sequence data methods
String Methods
In [1]: strSample = 'learning is fun !'
print(strSample)
learning is fun !
In [2]: strSample.capitalize( ) # returns the string with its first character capitalized and the rest lowercased
Out[2]: 'Learning is fun !'
In [3]: strSample.title() # to capitalise the first character of each word
Out[3]: 'Learning Is Fun !'
In [4]: strSample.swapcase() # to swap the case of strings
Out[4]: 'LEARNING IS FUN !'
In [5]: strSample.find('n') # to find the index of the given letter
Out[5]: 4
In [6]: strSample.count('a') # to count total number of 'a' in the string
Out[6]: 1
In [7]: strSample.replace('fun','joyful') # to repace the letters/word
Out[7]: 'learning is joyful !'
/
In [8]: strSample.isalnum() # Return true if all bytes in the sequence are
# alphabetical ASCII characters or ASCII decimal digits,
# false otherwise
Out[8]: False
In [10]: name1 = 'GITAA'
name2 = 'Pvt'
name3 = 'Ltd'
In [11]: name='{} {}. {}.'.format(name1,name2,name3)
print(name)
GITAA Pvt. Ltd.
The below code will show all the functions that we can use for the particular variable:
In [12]: print(dir(name))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute_
_', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__l
t__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr_
_', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isn
umeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
/
In [14]: print(help(str.find))
Help on method_descriptor:
find(...)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
None
Sequence datatype object initializations
In [15]: strSample = 'learning is fun !' # STRING
In [16]: lstSample = [1,2,'a','sam',2] # list
In [17]: from array import *
In [18]: arrSample = array('i',[1,2,3,4]) # array
In [19]: tupSample = (1,2,3,4,3,'py') # tuple
In [20]: dictSample= {1:'first', 'second':2, 3:3, 'four':'4'} # dictionary
/
In [33]: setSample = {'example',24,87.5,'data',24,'data'} # set
keys = (1,'second',3,'four')
rangeSample = range(1,12,4) # built-in sequence type used for looping
for x in rangeSample: print(x)
1
5
9
len(object) returns number of elements in the object
accepted object types: string, list, array, tuple, dictionary, set, range
In [21]: print("No. of elements in the object :")
print("string = {} , list= {}, array= {}, tuple = {},\
dictionary ={}, set ={}, range ={}".format(len(strSample), len(lstSample),
len(arrSample) , len(tupSample), len(dictSample), len(setSample), len(rangeSample)))
No. of elements in the object :
Traceback (most recent call last):
File "<ipython-input-21-8eafcd797341>", line 4, in <module>
len(arrSample) , len(tupSample), len(dictSample), len(setSample), len(rangeSample)))
NameError: name 'setSample' is not defined
In [22]: print(lstSample)
[1, 2, 'a', 'sam', 2]
/
In [23]: lstSample.reverse() # Reverses the order of the list
print(lstSample)
[2, 'sam', 'a', 2, 1]
The clear() method removes all items from the object
Supported sequence data: list, dictionary, set
In [24]: lstSample.clear()
print(lstSample)
[]
In [25]: dictSample.clear()
print(dictSample)
{}
In [26]: setSample.clear()
print(setSample)
Traceback (most recent call last):
File "<ipython-input-26-60ed937b48b7>", line 1, in <module>
setSample.clear()
NameError: name 'setSample' is not defined
append() Adds an element at the end of the object
Supported datatypes: array, list, set
/
In [27]: arrSample.append(3) # adding an element, 3 to the 'arrSample'
print(arrSample) # updated array, arrSample
array('i', [1, 2, 3, 4, 3])
In [28]: print(lstSample)
[]
In [29]: lstSample.append([2,4]) # adding [2, 4] list to lstSample
print(lstSample) # updated list
[[2, 4]]
In [34]: #setSample.append(20) # AttributeError: 'set' object has no attribute 'append'
setSample.add(20) # add() takes single parameter(element) which needs to
# be added in the set
print(setSample)
{'data', 20, 87.5, 24, 'example'}
update() function in set adds elements from a set (passed as an argument) to
the set
- This method takes only single argument
- The single argument can be a set, list, tuples or a dictionary
- It automatically converts into a set and adds to the set
In [35]: setSample.update([5,10]) # adding a list of elements to the set
print(setSample) # updated set
{'data', 5, 10, 20, 87.5, 24, 'example'}
Dictionary Methods
/
In [ ]: print(dictSample)
In [ ]: dictSample["five"] = 5
print(dictSample)
In [ ]: dictSample.update(five = 5) # update the dictionary with the key/value pairs from other,
# overwriting existing keys
print(dictSample) # updated dictionary
In [ ]: list(dictSample) # returns a list of all the keys used in the dictionary dictSample
In [ ]: len(dictSample) # returns the number of items in the dictionary
In [ ]: dictSample.get("five") # it is a conventional method to access a value for a key
In [ ]: dictSample.keys() # returns list of keys in dictionary
In [ ]: dictSample.items() # returns a list of (key, value) tuple pairs
insert()- inserts the element at the specified index of the object
- supported datatypes: array, list
In [ ]: print(arrSample)
In [ ]: arrSample.insert(1,100) # inserting the element 100 at 2nd position
print(arrSample) # printing array
In [ ]: lstSample.insert(5,24) # inserting the element 24 at 5th position
print(lstSample) # printing list
/
pop()- removes the element at the given index from the object and prints the
same
default value is -1, which returns the last item
supported datatypes: array, list, set, dictionary
In [ ]: arrSample.pop() # deleting the last element and prints the same
In [ ]: print(lstSample)
lstSample.pop(4) # deleting the 5th element from the list
In [ ]: print(dictSample)
dictSample.pop('second') # deleting the key - second
In [ ]: dictSample.pop(3) # deleting the key - 3
Set is an unordered sequence and hence pop is not usually used
The remove() method removes the first occurrence of the element with the
specified value
- supported datatypes: array, list, dictionary, set
In [ ]: print(arrSample)
In [ ]: arrSample.remove(0) # ValueError: array.remove(x): x not in list
/
In [ ]: arrSample.remove(2) # removes the element 2 from the array, arrSample
print(arrSample)
In [ ]: print(lstSample)
lstSample.remove('sam') # removes the element 'sam' from the list, lstSample
print(lstSample)
In [ ]: print(setSample)
setSample.remove(57) # KeyError: 57
In [ ]: setSample.discard(57) # The set remains unchanged if the element passed to
# discard() method doesn't exist
print(setSample)
del: deletes the entire object of any data type
- syntax: del obj_name
- del is a Python keyword
- obj_name can be variables, user-defined objects, lists, items
within lists, dictionaries etc.
In [ ]: del setSample # deleting the set, setSample
print(setSample) # NameError: name 'setSample' is not defined
In [ ]: del arrSample # deleting the array, arrSample
print(arrSample) # NameError: name 'arrSample' is not defined
In [ ]: del lstSample # deleting the list, lstSample
print(lstSample) # NameError: name 'lstSample' is not defined
In [ ]: del lstSample[2] # deleting the third item
print(lstSample)
/
In [ ]: del lstSample[1:3] # deleting elements from 2nd to 4th
print(lstSample)
In [ ]: del lstSample[:] # deleting all elements from the list
print(lstSample)
In [ ]: del dictSample # deleting the dictionary, dictSample
print(dictSample)
The extend() method adds the specified list elements (or any iterable - list, set,
tuple, etc.) to the end of the current list
Array operations
In [10]: arrSample.extend((4,5,3,5)) # add a tuple to the arrSample array:
print(arrSample)
array('i', [1, 2, 3, 4, 4, 5, 3, 5, 4, 5, 3, 5])
In [11]: print(arrSample.extend(['sam'])) # TypeError: an integer is required (got type str) - should match with itemcode of the array
Traceback (most recent call last):
File "<ipython-input-11-9f9b870f6629>", line 1, in <module>
print(arrSample.extend(['sam'])) # TypeError: an integer is required (got type str) - should match with itemcode of the arra
y
TypeError: an integer is required (got type str)
/
In [13]: arrSample.fromlist([3, 4]) # add values from a list to an array
print(arrSample)
arrSample.tolist() # to convert an array into an ordinary list with the same items
array('i', [1, 2, 3, 4, 4, 5, 3, 5, 4, 5, 3, 5, 3, 4, 3, 4])
Out[13]: [1, 2, 3, 4, 4, 5, 3, 5, 4, 5, 3, 5, 3, 4, 3, 4]
In [ ]: range
List operations
Create a list using loop and function
In [15]: def numbers(n):
return [i for i in range(1, n+1)]
In [16]: numbers(10)
Out[16]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Set operations
setSample
A set is an unordered collection of items
Every element is unique (no duplicates)
Sets can be used to perform mathematical set operations like
union, intersection, symmetric difference etc
/
In [17]: A = {'example',24,87.5,'data',24,'data'} # set of mixed data types
print(A)
{24, 'data', 'example', 87.5}
In [18]: B = {24, 87.5} # set of integers
print(B)
{24, 87.5}
In [20]: print(A | B) # union of A and B is a set of all elements from both sets
A.union(B) # using union() on B
{'example', 87.5, 24, 'data'}
Out[20]: {24, 87.5, 'data', 'example'}
In [21]: print(A & B) # intersection of A and B is a set of elements that are common in both sets
A.intersection(B) # using intersection() on B
{24, 87.5}
Out[21]: {24, 87.5}
END OF SCRIPT