0% found this document useful (0 votes)
4 views42 pages

Python Data Types and Functions Guide

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

Python Data Types and Functions Guide

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

Data types & its Functions

Data types:

 A data type is a classification of data


that specifies the kind of values a
variable can hold and the operations
that can be performed on it.

 Python has 5 Data Types. They are :-


 Numbers
 String
 List
 Tuple
 Dictionary.

(i)Numbers :

 Integers
 Floating-Point numbers
 Complex

(ii)Strings:

 Python Strings are immutable.

 A string is a sequence of characters


enclosed in either single quotes ('') or
double quotes (“”) .

 String functions :-

(i)len() function:
 It returns the length of its
argument string, (i. e) it
returns the count of characters
in the passed string.
 Syntax: len(<string>)
 Examples ,
>>>len(“hello”)
6
(ii) capitalize() function:
 It returns a copy of the string
with its first character
capitalaized.
 Syntax ,<string>.capitalize()
 Example ,
>>>’red’.capitalize()
Red
(iii) count() function:
 It returns the number of
occurrences of the substring
sub in string (or
string[start :end].
 Syntax,<string>.count (sub [,
start[, end] ] )
 Example ,
>>>
“abracadabra”.count(‘ab’)
2
>>>”abracadabra” .
count(‘ab’,4,8)
0
>>>”abracadabra” .
count(‘ab’ , 6)
1
(iv) find() function:
 It returns the lowest index
in the string where the
substring sub is found
within the slice range of
start and end.(Returns -1 if
sub is not found).
 Syntax ,<string>.find(sub
[,start[, end ]]])
 Example ,
>>>string=’it goes as –
ringa roses’
>>>sub=”ringa”
>>>[Link](sub)
13

(v) Index() function :


 It returns the lowest index
where the specified
substring is found. If the
substring is not found then
an exception, ValueError, is
raised.
 Syntax,<string>.index(sub[,
start[, end]])
 Example ,
>>>’abracadabra’.
index(‘ab’)
0
(vi) isalnum() function:
 It returns True if the
characters in the string are
alphanumeric
(alphabets/numeric) and
there is at least one
characters, False otherwise.
 Syntax,<string>. Isalnum()
 Example ,
>>>s1=’abc123’
>>>s2=’hello’
>>>s3=’12345’
>>>s4=’ ‘
>>>[Link]()
True
>>>[Link]()
True
>>>[Link]()
True
>>>[Link]()
False
(vii) isalpha() function:
 It returns True if the
characters in the string are
alphabetic and there is at
least one characters, False
otherwise.
 Syntax ,<string>.isalpha()
 Example ,
>>>s1=’abc123’
>>>s2=’hello’
>>>s3=’12345’
>>>s4=’ ‘
>>>[Link]()
False
>>>[Link]()
True
>>>[Link]()
False
>>>[Link]()
False
(viii) isdigit() function:
 It returns True if the
characters in the string are
digit and there is at least
one characters, False
otherwise.
 Syntax ,<string>.isdigit()
 Example ,

>>>s1=’abc123’
>>>s2=’hello’
>>>s3=’12345’
>>>s4=’ ‘
>>>[Link]()
False
>>>[Link]()
False
>>>[Link]()
True
>>>[Link]()
False
(ix) islower() function :
 It returns True if the

characters in the string are


lowercase and there is at
least one characters, False
otherwise.
 Syntax ,<string>.islower()
 Example ,

>>>s1=” “
>>>s2=””
>>>[Link]()
True
>>>[Link]()
False
(x) isspace() function:
 It returns True if there are

only whitespace characters


in the string.
 There must be at least one
character. It returns False
otherwise.
 Syntax, <string>.isspace()
 Example,
>>>s1=” “
>>>s2=””
>>>[Link]()
True
>>>[Link]()
False
(xi) isupper() function:
 It tests whether all cased
characters in the string are
uppercase and requires that
there be at least one cased
character.
 Returns True if so, False
otherwise.
 Syntax,<string>.isupper()

 Example,
>>>s1=”HELLO”
>>>s2=”There”
>>>s3=”goldy”
>>>s4=”U123”
>>>s5=”123f”
>>>[Link]()
True
>>>[Link]()
False
>>>[Link]()
False
>>>[Link]()
True
>>>[Link]()
False
(xii) lower() function:
 It returns a copy of the
string converted to
lowercase.
 Syntax,<string>.lower()
 Example,
>>>s1=”HELLO”
>>>s2=”There”
>>>s3=”goldy”
>>>s4=”U123”
>>>s5=”123f”
>>>[Link]()
‘hello’
>>>[Link]()
‘there’
>>>[Link]()
‘goldy’
>>>[Link]()
‘u123’
>>>[Link]()
‘123f’
(xiii) upper() function:
 It returns a copy of the
string converted to
uppercase.
 Syntax,<string>.upper()
 Example,
>>>s1=”HELLO”
>>>s2=”There”
>>>s3=”goldy”
>>>s4=”U123”
>>>s5=”123f”
>>>[Link]()
‘HELLO’
>>>[Link]()
‘THERE’
>>>[Link]()
‘GOLDY’
>>>[Link]()
‘U123’
>>>[Link]()
‘123F’
(xiv) Lstrip(),rstrip(),strip() function:
 lstrip():
 Returns a copy of the string

with leading whitespaces


removed, i.e., whitespaces
from the leftmost end are
removed.
 Syntax,<string>.lstrip()
 Example,
>>>” Sipo “.lstrip()
“Sipo “

 rstrip():
 Returns a copy of the string
with trailing whitespaces
removed, i.e., whitespaces
from the rightmost end are
removed.
 Syntax,<string>.rstrip()

 Example,

>>>’ Sipo “
‘ Sipo’
 strip():
 Returns a copy of the string

with leading and trailing


whitespaces removed, i.e.,
whitespaces from the
leftmost and the rightmost
ends are removed.
 Syntax,<string>.strip()
 Example,

>>>’ Sipo ‘
‘Sipo’
(xv) startswith(), endswith() function:
 startswith() :
 Returns True if the string

starts with the substring sub


, otherwise returns False.
 Syntax,<string>.startswith()

 Example,

>>>”abcd”.startswith(‘cd’)
False

>>>”abcd”.startswith(‘ab’)
True
 endswith():
 Returns True if the string

ends with the substring sub


, otherwise returns False.
 Syntax,<string>.endswith()

 Example,

>>>”abcd”.endswith(‘b’)
False
>>>”abcd”.endswith(‘cd’)
True
(xvi) title() functions:
 It returns a title-cased version

of the string where all words


start with uppercase characters
and all remaining letters are in
lowercase.
 Syntax,<string>.title()

 Example,

>>>”the sipo app”.title()


‘The Sipo App’
>>>”COMPUTER
SCIENCE” .title()
‘Computer Science’
(xvii) istitle() function:
 It returns True if the string has

the title case,(i.e., the first


letter of each word in
uppercase, while rest of the
letters in lowercase), False
otherwise.
 Syntax,<string>.istitle()

 Example,
>>>’ Computer Science
‘’ .istitle()
True
>>>’ COMPUTER SCIENCE
‘.istitle()
False
(xviii) replace() function:
 It returns a copy of the string

with all occurrences of


substring old replaced by new
string.
 Syntax,<string>.replace(old,

new)
 Example,

>>>’abracadabra’.replace(‘ab’,
’sp’)
‘spracadaspra’
(xix) join() function:
 It joins a string or character
(i.e., <str>) after each member
of the string iterator i.e., string
based sequence.
 Syntax,<string>.join(<string
iterable>)
 Example,(based on <str>);
>>>”*”.join(“Hello”)
‘H*e*l*l*o’
 Example,(based on list/tuple);

>>>”&&”.join([“trial”,”hello”])
‘trail&&hello’
(xx) split() function:
 It splits a string(i.e.,<str>)
based on given string or
character(i.e., <string/char>)
and returns a list containing
split strings as members.
 Syntax,<string>.split(<string/
char>)
 Example,
>>>”I Love [Link]()
[‘I’ , ‘Love’ , ‘Python’]
(xxi) partition() function:
 The partition() function splits the
string at the first occurrence of
separator, and returns a tuple
containing three items.
 Syntax,
<string>.partition(<separator/
string>)
 Example,
>>>txt=”I enjoy working in
Python"
>>>x=[Link](“working”)
>>>print(x)
(‘I enjoy’, ‘working’ , ‘in
Python’)

(iii)Lists:

 Python lists are mutable,


(i.e.,)we can change the
elements of a list in place.
->List functions:

(i) len() functions:


 Returns the length of its
argument list, i.e., it returns the
number of elements in the
passed list. The len() function is
a Python standard library
function.
 Syntax,len(<list>)
 Example,
>>>len( [1, 3, 2] )
3
(ii) list() function:
 Returns a list created from the
passed argument, which should
be a sequence type (string, list,
tuple, etc.). If no argument is
passed, it will create an empty
list.
 Syntax, list([<sequence>])
 Example,
>>>list(“hello”)
[‘h’,’e’,’l’,’l’,’o’]

(iii) index() function:


 Returns the index of first
matched item from the list.
 Syntax, [Link](<item>)
 Example,
>>>L1=[13, 18, 11, 16, 18,
14]
>>>[Link](18)
1
(iv) append() function:
 This method adds an item to the
end of the list.
 Syntax, [Link](<item>)
 Example,
>>>colours=[‘red’, ‘green’,
‘blue’]
>>>[Link](‘yellow’)
>>>colours
[‘red’, ‘green’, ‘blue’, ‘yellow’]
 Append() does not create a new
list.

(v) extend() functions:


 This method is used to add
multiple elements.
 Syntax, [Link](<list>)
 Example,
>>>t1=[‘a’, ‘b’, ‘c’]
>>>t2=[‘d’, ‘e’]
>>>[Link](t2)
>>>t1
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
(vi) insert() functions:
 This method inserts an item at a
given position.
 Syntax,
[Link]( <ind>,<item>)
 Example,
>>>t1=[‘a’, ‘c’, ‘d’]
>>>[Link](2, ‘b’)
>>>t1
[‘a’, ‘b’, ‘c’, ‘d’]
(vii) pop() functions:
 This method is used to remove
an item from the list.
 Syntax, [Link](<index>)
 Example,
>>>t1=[‘a’ ,’e’, ‘i’, ‘o’, ‘u’, ‘b’]
>>>[Link](5)
>>>t1
[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
(ix) remove() function:
 This method removes the first
occurrence of the given item
from the list.
 Syntax, [Link](<value>)
 Example,
>>>t1=[‘a’, ‘a’]
>>>[Link](‘a’)
>>>t1
[‘a’]

(x) clear() function:


 This method removes all the
items from the list and the list
becomes empty list after this
function. This function returns
nothing.
 Syntax, [Link]()
 Example,
>>>L1=[2, 3, 4, 5]
>>>[Link]()
>>>L1
[]
(x) count() function:
 This function returns the count of
an item that you passed as
argument. If the given item is
not in the list, it returns zero.
 Syntax, [Link](<item>)

 Example,

>>>L1=[13, 18, 20, 10,


18, 23]

>>>[Link](18)

(xi) reverse() function:


 This reverses the item of the list,
it does not create a new list.
 Syntax, [Link]()
 Example,
>>>t1
[‘e’, ‘i’, ‘q’, ‘a’, ‘q’, ‘p’]
>>>[Link]()
[‘p’, ‘q’, ‘a’, ‘q’, ‘i’, ‘e’]
(xii) sort() function:
 This function sorts the items of
the list, by default in increasing
order, it does not create a new
list.
 Syntax,
[Link]([reverse=False/True])
 Example,
>>>t1=[‘e’, ‘a’, ‘q’, ‘b’]
>>>[Link]()
>>>t1
[‘a’, ‘b’, ‘e’ ,’q’]
(xiii) sorted() function:
 This function takes the name of
the list as an argument and
returns a new sorted list with
sorted elements in it.
 Syntax,
sorted(<iterable_sequence>,
[reverse=False])
-If reverse argument is set to
False the argument is sorted in
ascending order. If reverse
argument is set to True
argument is sorted in
descending order.
 Example,
>>>val=[17, 24, 15, 30]
>>>sval=sorted(val)
>>>sval
[15, 17, 24, 30]
(xiv) min(), max(), sum():
 These functions take the list
sequence and return the
minimum element, maximum
element, sum of all element of
the list.
 Syntax,
min(<list>)
max(<list>)
sum(<list>)
 Example,
>>>val=[17,24,15,30]
>>>min(val)
15
>>>max(val)
30
>>>sum(val)
86

->Tuples functions:-

(i) len() function:


 This method returns the length
of the tuple.
 Syntax, len(<tuple>)
 Example,
>>>employee=(‘John’, 10000,
24, ‘Sales’)
>>>len(employee)
4
(ii) max() function:
 This method returns the element
from the tuple having the
maximum value.
 Syntax, max(<tuple>)
 Example,

>>>tpl=(10, 12, 14, 20, 22, 24,


30, 32, 34)
>>>max(tpl)
>>>34

(iii) min() function:


 This method returns the

element from the tuple having


minimum value.
 Syntax, min(<tuple>)

 Example,
>>>min(tpl)
10
(iv) sum() function:
 This function takes the tuple

sequence and returns the sum of


the elements of the tuple.
 Syntax, sum(<tuple>)

 Example,

>>>Val=[21,9]
>>>sum(val)
30
(v) index() function:
 This method returns the index of

the element of a tuple.


 Syntax,

<tuplename>.index(<item>)
 Example,

 >>>t1=[3, 4, 5, 6.0]

>>>[Link](5)
2
(vi) count() function:
 This method returns the count of

a member element/object in a
given sequence(list/tuple).
 Syntax,
<sequence_name>.count(<obje
ct>)
 Example,

>>>t1=(2,2,2,5)
>>>[Link](2)
3
(vii) sorted() function:
 This method returns a new

sorted list with sorted elements


in it.
 Syntax,

sorted(<iterable_sequence>,
[reverse=False]
 Example,

>>>val=[27,34,25,40]
>>>sval
[27,25,34,40]
(viii) tuple() function:
 This method can be used to

create tuples from different


types of values.
 Syntax, tuple(<sequence>)

 Example,
>>>t=tuple(‘abc’)
>>>t
(‘a’, ‘b’, ‘c’)

->Dictionary functions:-
->Get length of the dictionary
(i) len() function:
 To get the length of the
dictionary, i.e., the count of the
key:value pair, we can use the
len() function. This function
returns length of the dictionary,
i.e., the count of
elements(key:value pairs) in the
dictionary.
 Syntax, len(<dictionary>)

 Example,
>>>emp={‘name’:’John’,’salary
':10000,
‘age’:24}
>>>len(emp)

->Accessing Items, Keys and Values:-

(ii) get() function:


 We can get the item with the
given key, similar to
dictionary[key].If the key is not
present, Python by default gives
error.
 Syntax,<dictionary>.get(key,
[default])
 Example,
>>>empI
{‘salary’:10000,’dept’:’sales’,’ag
e’:24,’name’:’john’}
>>>[Link](‘dept’)
‘sales’
(iii) items() function:
 This method returns all of the
items in the dictionary as a
sequence of(key, value)tuples.
 Syntax, <dictionary>.items()
 Example,
>>>employee={‘name’:’John’,’s
alary’:10000,’age’:24}
>>>mylist=[Link]()
>>>for x in mylist:
Print(x)
(iv) keys() function:
 This method returns all of the
keys in the dictionary as a
sequence of keys(in form of a
list).
 Syntax, <dictionary>.keys()
 Example,
>>>employee=={‘name’:’John’,
’salary’:10000,’age’:24}
>>>[Link]()
[‘salary’,’dept’,’age’,’name’]
(v) values() function:
 This method returns all the
values from the dictionary as a
sequence(a list).
 Syntax, <dictionary>.values()
 Example,
>>>employee=={‘name’:’John’,
’salary’:10000,’age’:24}
>>>[Link]()
[10000,’sales’,24,’John’]

->Creating Dictionary from keys:-

(i) fromkeys() function:


 Thus method is used to create a
new dictionary from a sequence
containing all the keys and a
common bvalueb, which will be
assigned to all the keys.
 Syntax, [Link](<key
sequence>,[<value>])
 Example,
>>>nd1=[Link]((3, 4,
5))
>>>nd1
{3:None, 4:None, 5:None}

->Extend/Update Dictionary with new


key:-

(i) setdefault() function:


 This method inserts a new key
and value pair ONLY IF the key
doesn’t already exist. If the key
already exists, it returns the
current value of the key.
 Syntax,
[Link](<key>,<value>)
 Example,
>>>marks={1:350,2:423,3:411,
4:300}
>>>[Link](5, 320)
320
>>>marks
{1:350,2:423,3:411,4:300,5:320
}
(ii) update() function:
agThis method merges key:value
pairs from the new dictionary
into the original dictionary,
adding or replacing as needed.
The items in the new dictionary
are added to the old one and
override any items already there
with the same keys.
 Syntax,
<dictionary>.update(<other-
dictionary>)
 Example,
>>>emp1={‘name’:’John’,’salar
y’:10000,’age’:24}
>>>emp2={‘name’:’Diya’,’salar
y’:54000,’dept’:’Sales’}
>>>[Link](emp2)
>>>emp1
{‘salary’:54000,’dept’:’sales’,’na
me’:’Diya’,’age’:24}
>>>emp2
{‘salary’:54000,’dept’:’sales’,’na
me’:’Diya’}

->Deleting Elements from Dictionary:-

(i) pop() function:


 This method removes and
returns the dictionary element
associated to passed key.
 Syntax,
<dict>.pop(key,<value>)
 Example,
>>>stu
{1:’Neha’, 2:’Saima’,
3:’Avnit’,4’Ana’}
>>>[Link](4)
‘Ana’

(ii) popitem() function:


 This method removes and
returns a (key,value)pair from
the [Link] returns the
items in the LIFO(last In First
Out) order.
 Syntax, <dict>.popitem()
 Example,
>>>stu
{1:’Neha’, 2:’Saima’,
3:’Avnit’,4’Ana’}
>>>[Link]()
(4:’Ana’)
(iii) clear() function:
 This method removes all items
from the dictionary and the
dictionary becomes empty
dictionary post this method.
 Syntax, <dictionary>.clear()
 Example,
>>>emp={‘name’:’John’,’salary
’:10000,’age’:24}
>>>[Link]()
>>>emp
{}

->Get Sorted list of Keys:-

(i) sorted() function:


 This function can considers only
the keys of the dictionary for
sorting and returns a sorted list
of the dictionary keys.
 Syntax, sorted(<dict>,
[reverse=False])
 Example,
>>>stu={19:’Neha’,12:’Saima’,
37:’Avnit’,42’Ana’}
>>>lst=sorted(stu)
>>>lst
[12, 19, 37, 42]

->Calculating Maximum, Minimum


and Sum:-

(i) minimum, maximum, sum()


function:
 We can apply the max(), min(),
sum() functions on dictionaries
too. These function work with
keys of a dictionary and thus for
these function to work, the
dictionary keys must be
homogeneous types.
 Syntax, max(<dict>),
min(<dict>), sum(<dict>)
 Example,
>>>d1
{(1, 2):’One’, (3, 4):’Two’}
>>>d2
{‘Green house’:20, ‘Blue
house’:30, ‘gray house’:35}
>>>d3
{41:’N’,12:’S’,3.2:’A’,2.4:’C’}
>>>d4
{1.5:’N’,3.5:’S’,3.2:’A’,2.4:’C’}
Now examples,
>>>min(d1),min(d2),min(d3),mi
n(d4)
((1,2),’green house’,12,1.5)
>>>max(d1),max(d2),max(d3),
max(d4)
((3,4),’Gray house’,41,3.5)
>>>sum(d1),sum(d2),sum(d3),s
um(d4)
TypeError

You might also like