SlideShare a Scribd company logo
1 of 33
Mutable Vs Immutable Objects
In general, data types in Python can be distinguished based
on whether objects of the type are mutable or immutable.
The content of objects of immutable types cannot be
changed after they are created.
Mutable Objects Immutable Objects
byte array
list
set
dict
int, float, long,
complex
str
tuple
frozen set
Python Data Types
Python´s built-in (or standard) data types can be
grouped into several classes.
Boolean Types
Numeric Types
 Sequences
 Sets
 Mappings
Boolean Types:
The type of the built-in values True and False. Useful in
conditional expressions, and anywhere else you want to
represent the truth or falsity of some condition. Mostly
interchangeable with the integers 1 and 0.
Examples:
Numeric Types:
Python supports four different numerical types :
1) int (signed integers)
2) long (long integers [can also be represented in octal and
hexadecimal])
3) float (floating point real values)
4) complex (complex numbers)
Integers
Examples: 0, 1, 1234, -56
 Integers are implemented as C longs
 Note: dividing an integer by another integer will return only
the integer part of the quotient, e.g. typing 7/2 will yield 3
Long integers
Example: 999999999999999999999L
 Must end in either l or L
 Can be arbitrarily long
Floating point numbers
Examples: 0., 1.0, 1e10, 3.14e-2, 6.99E4
 Implemented as C doubles
 Division works normally for floating point numbers: 7./2.
= 3.5
 Operations involving both floats and integers will yield
floats:
6.4 – 2 = 4.4
Octal constants
Examples: 0177, -01234
 Must start with a leading ‘0’
Hex constants
Examples: 0x9ff, 0X7AE
 Must start with a leading ‘0x’ or ‘0X’
Complex numbers
Examples: 3+4j, 3.0+4.0j, 2J
 Must end in j or J
 Typing in the imaginary part first will return the complex
number in the order Re+ ImJ
Sequences
There are five sequence types
1) Strings
2) Lists
3) Tuple
4) Bytearray
5) Xrange
1. Strings:
 Strings in Python are identified as a contiguous set of
characters in between quotation marks.
 Strings are ordered blocks of text
 Strings are enclosed in single or double quotation marks
 Double quotation marks allow the user to extend strings
over multiple lines without backslashes, which usually
signal the continuation of an expression
Examples: 'abc', “ABC”
Concatenation and repetition
Strings are concatenated with the + sign:
>>> 'abc'+'def'
'abcdef'
Strings are repeated with the * sign:
>>> 'abc'*3
'abcabcabc'
Indexing and Slicing
 Python starts indexing at 0. A string s will have indexes running from
0 to len(s)-1 (where len(s) is the length of s) in integer quantities.
s[i] fetches the ith element in s
>>> s = 'string'
>>> s[1] # note that Python considers 't' the first element
't' # of our string s
s[i:j] fetches elements i (inclusive) through j (not inclusive)
>>> s[1:4]
'tri'
s[:j] fetches all elements up to, but not including j
>>> s[:3]
'str'
s[i:] fetches all elements from i onward (inclusive)
>>> s[2:]
'ring'
s[i:j:k] extracts every kth element starting with index i
(inlcusive) and ending with index j (not inclusive)
>>> s[0:5:2]
'srn'
Python also supports negative indexes. For example, s[-1]
means extract the first element of s from the end (same as
s[len(s)-1])
>>> s[-1]
'g'
>>> s[-2]
'n‘
One of Python's coolest features is the string
format operator %. This operator is unique to strings and
makes up for the pack of having functions from C's printf()
family.
Some of the string methods are listed in below:
str.capitalize ( )
str.center(width[, fillchar])
str.count(sub[, start[, end]])
str.encode([encoding[, errors]])
str.decode([decoding[, errors]])
str.endswith(suffix[, start[, end]])
str.find(sub[, start[, end]])
str.isalnum()
str.isalpha()
str.isdigit()
str.islower()
str.isspace()
Sample Program for String Methods
var1='Hello World!'
var2='Python Programming'
print 'var1[0]: ',var1[0]
print 'var2[0:6]:',var2[0:6]
print 'Updatestring:-',var1[:6]+'Python'
print var1*2
print "My name is %s and dob is
%d"%('Python',1990)
# first character capitalized in string
str1='guido van rossum'
print str1.capitalize()
print str1.center(30,'*‘)
sub='s';
print 'str1.count(sub,0):-',str1.count(sub,0)
sub='van'
print 'str1.count(sub):-',str1.count(sub)
str1=str1.encode('base64','strict')
print 'Encoding string :'+str1
print 'Decode string :'+str1.decode('base64','strict')
str2='Guido van Rossum'
suffix='Rossum'
print str2.endswith(suffix)
print str2.endswith(suffix,1,17)
# find string in a existed string or not
str4='Van'
print str2.find(str4)
print str2.find(str4,17)
str5='sectokphb10k'
print str5.isalnum()
str6='kumar pumps'
print str6.isalnum()
print str4.isalpha()
str7='123456789'
print str7.isdigit()
print str6.islower()
print str2.islower()
str8=' '
print str8.isspace()
Output for the string methods sample code
2) Lists
Lists are positionally ordered collections of arbitrarily typed
objects, and they have no fixed size and they are mutable.
 Lists are contained in square brackets []
 Lists can contain numbers, strings, nested sublists, or
nothing
Examples:
L1 = [0,1,2,3],
L2 = ['zero', 'one'],
L3 = [0,1,[2,3],'three',['four,one']],
L4 = []
 List indexing works just like string indexing
 Lists are mutable: individual elements can be reassigned in
place. Moreover, they can grow and shrink in place
Example:
>>> L1 = [0,1,2,3]
>>> L1[0] = 4
>>> L1[0]
4
Basic List Operations
Lists respond to the + and * operators much like
strings; they mean concatenation and repetition here
too, except that the result is a new list, not a string.
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration
Some of the List methods are listed in below
list.append(obj)
list.count(obj)
list.extend(seq)
list.index(obj)
list.insert(index, obj)
list.pop(obj=list[-1])
list.remove(obj)
listlist.reverse()
list.sort([func])
Sample Code for List Methods
list1=['python','cython','jython']
list1.append('java')
print list1
list1.insert(2,'c++')
print list1
list2=['bash','perl','shell','ruby','perl']
list1.extend(list2)
print list1
if 'python' in list1:
print 'it is in list1'
if 'perl' in list2:
print 'it is in list2'
# reversing the list
list1.reverse()
print list1
# sorting the list
list2.sort()
print list2
# count the strings in list
value=list2.count('perl')
print value
# Locate string
index=list1.index("jython")
print index,list1[index]
Output for the list methods sample code
3) Tuple:
 A tuple is a sequence of immutable Python objects. Tuples are
sequences, just like lists.
 The only difference is that tuples can't be changed i.e., tuples are
immutable and tuples use parentheses and lists use square brackets.
 Tuples are contained in parentheses ()
 Tuples can contain numbers, strings, nested sub-tuples, or nothing
Examples:
t1 = (0,1,2,3)
t2 = ('zero', 'one')
t3 = (0,1,(2,3),'three',('four,one'))
t4 = ()
Basic Tuple Operations
Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too, except that
the result is a new tuple, not a string.
Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
['Hi!'] * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 1 2 3 Iteration
4) Bytearray:
bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray type is a mutable
sequence of integers in the range 0 <= x < 256. The
optional source parameter can be used to initialize the array in a few
different ways:
If it is a string, you must also give the encoding (and
optionally, errors) parameters; bytearray() then converts the string to
bytes using str.encode()
If it is an integer, the array will have that size and will be initialized
with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer
of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the
range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
5) Xrange:
The xrange type is an immutable sequence which is
commonly used for looping. The advantage of the xrange type is
that an xrange object will always take the same amount of
memory, no matter the size of the range it represents. There are no
consistent performance advantages.
XRange objects have very little behavior: they only support
indexing, iteration, and the len( ) function.
Sets
The sets module provides classes for
constructing and manipulating unordered collections of
unique elements.
Common uses include membership testing,
removing duplicates from a sequence, and computing
standard math operations on sets such as intersection, union,
difference, and symmetric difference.
Curly braces or the set() function can be used to
create sets.
Sets Operations
Operation Equivalent Result
len(s) cardinality of set s
x in s test x for membership in s
x not in s test x for non-membership in s
s.issubset(t) s <= t test whether every element in s is in t
s.issuperset(t) s >= t test whether every element in t is in s
s.union(t) s | t
new set with elements from
both s and t
s.intersection(t) s & t
new set with elements common
to s and t
s.difference(t) s - t
new set with elements in s but not
in t
s.symmetric_difference(t) s ^ t
new set with elements in
either s or t but not both
s.copy() new set with a shallow copy of s
Operation Equivalent Result
s.update(t) s |= t
return set s with elements added
from t
s.intersection_update(t) s &= t
return set s keeping only elements
also found in t
s.difference_update(t) s -= t
return set s after removing
elements found in t
s.symmetric_difference_update(t) s ^= t
return set s with elements
from s or t but not both
s.add(x) add element x to set s
s.remove(x)
remove x from set s;
raises KeyError if not present
s.discard(x) removes x from set s if present
s.pop()
remove and return an arbitrary
element from s; raises KeyError if
empty
s.clear() remove all elements from set s
Mapping Type
 A mapping object maps hashable values to arbitrary objects.
Mappings are mutable objects. There is currently only one standard
mapping type, the dictionary.
 Dictionaries consist of pairs (called items) of keys and
their corresponding values.
Dictionaries can be created by placing a comma-separated list
of key: value pairs within curly braces
Keys are unique within a dictionary while values may not be. The
values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Example:
d={‘python’:1990,’cython’:1995,’jython’:2000}
Some of the dictionary methods listed in below
len( dict )
dict.copy( )
dict.items( )
dict.keys( )
dict.values( )
dict.has_key(‘key’)
viewitems( )
viewkeys( )
viewvalues( )
Sample code for dictionary methods
dict = {'Language': 'Python', 'Founder': 'Guido Van Rossum'}
print dict
print "Length of dictionary : %d" % len(dict)
copydict = dict.copy()
print "New Dictionary : %s" % str(copydict)
print "Items in dictionary: %s" % dict.items()
print "Keys in dictionary: %s" % dict.keys()
print "Vales in Dictionary: %s" % dict.values()
print "Key in dictionary or not: %s" % dict.has_key('Language')
print "Key in dictionary or not: %s" % dict.has_key('Year')
Output for the dictionary sample code

More Related Content

What's hot (20)

Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
NumPy
NumPyNumPy
NumPy
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Python recursion
Python recursionPython recursion
Python recursion
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Python Basics
Python BasicsPython Basics
Python Basics
 

Viewers also liked

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonSujith Kumar
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutAudrey Roy
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 

Viewers also liked (6)

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 

Similar to Python Datatypes by SujithKumar

Similar to Python Datatypes by SujithKumar (20)

Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
 
Chapter - 2.pptx
Chapter - 2.pptxChapter - 2.pptx
Chapter - 2.pptx
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
Python data handling
Python data handlingPython data handling
Python data handling
 
009 Data Handling .pptx
009 Data Handling .pptx009 Data Handling .pptx
009 Data Handling .pptx
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
unit 1.docx
unit 1.docxunit 1.docx
unit 1.docx
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdfupdated_tuple_in_python.pdf
updated_tuple_in_python.pdf
 
Python data type
Python data typePython data type
Python data type
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 

Recently uploaded

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Recently uploaded (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Python Datatypes by SujithKumar

  • 1.
  • 2. Mutable Vs Immutable Objects In general, data types in Python can be distinguished based on whether objects of the type are mutable or immutable. The content of objects of immutable types cannot be changed after they are created. Mutable Objects Immutable Objects byte array list set dict int, float, long, complex str tuple frozen set
  • 3. Python Data Types Python´s built-in (or standard) data types can be grouped into several classes. Boolean Types Numeric Types  Sequences  Sets  Mappings
  • 4. Boolean Types: The type of the built-in values True and False. Useful in conditional expressions, and anywhere else you want to represent the truth or falsity of some condition. Mostly interchangeable with the integers 1 and 0. Examples:
  • 5. Numeric Types: Python supports four different numerical types : 1) int (signed integers) 2) long (long integers [can also be represented in octal and hexadecimal]) 3) float (floating point real values) 4) complex (complex numbers)
  • 6. Integers Examples: 0, 1, 1234, -56  Integers are implemented as C longs  Note: dividing an integer by another integer will return only the integer part of the quotient, e.g. typing 7/2 will yield 3 Long integers Example: 999999999999999999999L  Must end in either l or L  Can be arbitrarily long
  • 7. Floating point numbers Examples: 0., 1.0, 1e10, 3.14e-2, 6.99E4  Implemented as C doubles  Division works normally for floating point numbers: 7./2. = 3.5  Operations involving both floats and integers will yield floats: 6.4 – 2 = 4.4
  • 8. Octal constants Examples: 0177, -01234  Must start with a leading ‘0’ Hex constants Examples: 0x9ff, 0X7AE  Must start with a leading ‘0x’ or ‘0X’ Complex numbers Examples: 3+4j, 3.0+4.0j, 2J  Must end in j or J  Typing in the imaginary part first will return the complex number in the order Re+ ImJ
  • 9. Sequences There are five sequence types 1) Strings 2) Lists 3) Tuple 4) Bytearray 5) Xrange
  • 10. 1. Strings:  Strings in Python are identified as a contiguous set of characters in between quotation marks.  Strings are ordered blocks of text  Strings are enclosed in single or double quotation marks  Double quotation marks allow the user to extend strings over multiple lines without backslashes, which usually signal the continuation of an expression Examples: 'abc', “ABC”
  • 11. Concatenation and repetition Strings are concatenated with the + sign: >>> 'abc'+'def' 'abcdef' Strings are repeated with the * sign: >>> 'abc'*3 'abcabcabc'
  • 12. Indexing and Slicing  Python starts indexing at 0. A string s will have indexes running from 0 to len(s)-1 (where len(s) is the length of s) in integer quantities. s[i] fetches the ith element in s >>> s = 'string' >>> s[1] # note that Python considers 't' the first element 't' # of our string s s[i:j] fetches elements i (inclusive) through j (not inclusive) >>> s[1:4] 'tri' s[:j] fetches all elements up to, but not including j >>> s[:3] 'str' s[i:] fetches all elements from i onward (inclusive) >>> s[2:] 'ring'
  • 13. s[i:j:k] extracts every kth element starting with index i (inlcusive) and ending with index j (not inclusive) >>> s[0:5:2] 'srn' Python also supports negative indexes. For example, s[-1] means extract the first element of s from the end (same as s[len(s)-1]) >>> s[-1] 'g' >>> s[-2] 'n‘ One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family.
  • 14. Some of the string methods are listed in below: str.capitalize ( ) str.center(width[, fillchar]) str.count(sub[, start[, end]]) str.encode([encoding[, errors]]) str.decode([decoding[, errors]]) str.endswith(suffix[, start[, end]]) str.find(sub[, start[, end]]) str.isalnum() str.isalpha() str.isdigit() str.islower() str.isspace()
  • 15. Sample Program for String Methods var1='Hello World!' var2='Python Programming' print 'var1[0]: ',var1[0] print 'var2[0:6]:',var2[0:6] print 'Updatestring:-',var1[:6]+'Python' print var1*2 print "My name is %s and dob is %d"%('Python',1990) # first character capitalized in string str1='guido van rossum' print str1.capitalize() print str1.center(30,'*‘) sub='s'; print 'str1.count(sub,0):-',str1.count(sub,0) sub='van' print 'str1.count(sub):-',str1.count(sub) str1=str1.encode('base64','strict') print 'Encoding string :'+str1 print 'Decode string :'+str1.decode('base64','strict') str2='Guido van Rossum' suffix='Rossum' print str2.endswith(suffix) print str2.endswith(suffix,1,17) # find string in a existed string or not str4='Van' print str2.find(str4) print str2.find(str4,17) str5='sectokphb10k' print str5.isalnum() str6='kumar pumps' print str6.isalnum() print str4.isalpha() str7='123456789' print str7.isdigit() print str6.islower() print str2.islower() str8=' ' print str8.isspace()
  • 16. Output for the string methods sample code
  • 17. 2) Lists Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size and they are mutable.  Lists are contained in square brackets []  Lists can contain numbers, strings, nested sublists, or nothing Examples: L1 = [0,1,2,3], L2 = ['zero', 'one'], L3 = [0,1,[2,3],'three',['four,one']], L4 = []
  • 18.  List indexing works just like string indexing  Lists are mutable: individual elements can be reassigned in place. Moreover, they can grow and shrink in place Example: >>> L1 = [0,1,2,3] >>> L1[0] = 4 >>> L1[0] 4
  • 19. Basic List Operations Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string. Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration
  • 20. Some of the List methods are listed in below list.append(obj) list.count(obj) list.extend(seq) list.index(obj) list.insert(index, obj) list.pop(obj=list[-1]) list.remove(obj) listlist.reverse() list.sort([func])
  • 21. Sample Code for List Methods list1=['python','cython','jython'] list1.append('java') print list1 list1.insert(2,'c++') print list1 list2=['bash','perl','shell','ruby','perl'] list1.extend(list2) print list1 if 'python' in list1: print 'it is in list1' if 'perl' in list2: print 'it is in list2' # reversing the list list1.reverse() print list1 # sorting the list list2.sort() print list2 # count the strings in list value=list2.count('perl') print value # Locate string index=list1.index("jython") print index,list1[index]
  • 22. Output for the list methods sample code
  • 23. 3) Tuple:  A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.  The only difference is that tuples can't be changed i.e., tuples are immutable and tuples use parentheses and lists use square brackets.  Tuples are contained in parentheses ()  Tuples can contain numbers, strings, nested sub-tuples, or nothing Examples: t1 = (0,1,2,3) t2 = ('zero', 'one') t3 = (0,1,(2,3),'three',('four,one')) t4 = ()
  • 24. Basic Tuple Operations Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string. Python Expression Results Description len((1, 2, 3)) 3 Length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ['Hi!'] * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x, 1 2 3 Iteration
  • 25. 4) Bytearray: bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. The optional source parameter can be used to initialize the array in a few different ways: If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode() If it is an integer, the array will have that size and will be initialized with null bytes. If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array. If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array. Without an argument, an array of size 0 is created.
  • 26. 5) Xrange: The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. XRange objects have very little behavior: they only support indexing, iteration, and the len( ) function.
  • 27. Sets The sets module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference. Curly braces or the set() function can be used to create sets.
  • 28. Sets Operations Operation Equivalent Result len(s) cardinality of set s x in s test x for membership in s x not in s test x for non-membership in s s.issubset(t) s <= t test whether every element in s is in t s.issuperset(t) s >= t test whether every element in t is in s s.union(t) s | t new set with elements from both s and t s.intersection(t) s & t new set with elements common to s and t s.difference(t) s - t new set with elements in s but not in t s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both s.copy() new set with a shallow copy of s
  • 29. Operation Equivalent Result s.update(t) s |= t return set s with elements added from t s.intersection_update(t) s &= t return set s keeping only elements also found in t s.difference_update(t) s -= t return set s after removing elements found in t s.symmetric_difference_update(t) s ^= t return set s with elements from s or t but not both s.add(x) add element x to set s s.remove(x) remove x from set s; raises KeyError if not present s.discard(x) removes x from set s if present s.pop() remove and return an arbitrary element from s; raises KeyError if empty s.clear() remove all elements from set s
  • 30. Mapping Type  A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.  Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Example: d={‘python’:1990,’cython’:1995,’jython’:2000}
  • 31. Some of the dictionary methods listed in below len( dict ) dict.copy( ) dict.items( ) dict.keys( ) dict.values( ) dict.has_key(‘key’) viewitems( ) viewkeys( ) viewvalues( )
  • 32. Sample code for dictionary methods dict = {'Language': 'Python', 'Founder': 'Guido Van Rossum'} print dict print "Length of dictionary : %d" % len(dict) copydict = dict.copy() print "New Dictionary : %s" % str(copydict) print "Items in dictionary: %s" % dict.items() print "Keys in dictionary: %s" % dict.keys() print "Vales in Dictionary: %s" % dict.values() print "Key in dictionary or not: %s" % dict.has_key('Language') print "Key in dictionary or not: %s" % dict.has_key('Year')
  • 33. Output for the dictionary sample code