SlideShare a Scribd company logo
Python Datatypes by SujithKumar
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

PPTX
Introduction to python for Beginners
Sujith Kumar
 
PPTX
Introduction to Basics of Python
Elewayte
 
PPTX
Data types in python
RaginiJain21
 
PPT
MySQL ppt
AtharvaSawant10
 
PPTX
Masterclass with super investors Part 1.pptx
RishabhShah368192
 
PPTX
Machine Learning - Splitting Datasets
Andrew Ferlitsch
 
PPTX
Functions in python slide share
Devashish Kumar
 
PPTX
Lecture-12Evaluation Measures-ML.pptx
GauravSonawane51
 
Introduction to python for Beginners
Sujith Kumar
 
Introduction to Basics of Python
Elewayte
 
Data types in python
RaginiJain21
 
MySQL ppt
AtharvaSawant10
 
Masterclass with super investors Part 1.pptx
RishabhShah368192
 
Machine Learning - Splitting Datasets
Andrew Ferlitsch
 
Functions in python slide share
Devashish Kumar
 
Lecture-12Evaluation Measures-ML.pptx
GauravSonawane51
 

What's hot (20)

PDF
Datatypes in python
eShikshak
 
PDF
Python-03| Data types
Mohd Sajjad
 
PDF
Set methods in python
deepalishinkar1
 
PDF
Character Array and String
Tasnima Hamid
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PPTX
Stream classes in C++
Shyam Gupta
 
PPT
Python List.ppt
T PRIYA
 
PDF
Python basic
Saifuddin Kaijar
 
PPT
Array in c
Ravi Gelani
 
PDF
Introduction to NumPy (PyData SV 2013)
PyData
 
PDF
Python libraries
Prof. Dr. K. Adisesha
 
PPTX
Type casting in java
Farooq Baloch
 
PPTX
Python Programming Language
Laxman Puri
 
PPTX
NUMPY-2.pptx
MahendraVusa
 
PPTX
C functions
University of Potsdam
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPTX
Strings in C
Kamal Acharya
 
PPTX
OOP concepts -in-Python programming language
SmritiSharma901052
 
Datatypes in python
eShikshak
 
Python-03| Data types
Mohd Sajjad
 
Set methods in python
deepalishinkar1
 
Character Array and String
Tasnima Hamid
 
Regular expressions in Python
Sujith Kumar
 
Stream classes in C++
Shyam Gupta
 
Python List.ppt
T PRIYA
 
Python basic
Saifuddin Kaijar
 
Array in c
Ravi Gelani
 
Introduction to NumPy (PyData SV 2013)
PyData
 
Python libraries
Prof. Dr. K. Adisesha
 
Type casting in java
Farooq Baloch
 
Python Programming Language
Laxman Puri
 
NUMPY-2.pptx
MahendraVusa
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Strings in C
Kamal Acharya
 
OOP concepts -in-Python programming language
SmritiSharma901052
 
Ad

Similar to Python Datatypes by SujithKumar (20)

PPTX
Python Session - 3
AnirudhaGaikwad4
 
PPTX
Introduction To Programming with Python-3
Syed Farjad Zia Zaidi
 
PPTX
PRESENTATION ON STRING, LISTS AND TUPLES IN PYTHON.pptx
kirtisharma7537
 
PPT
PPS_Unit 4.ppt
KundanBhatkar
 
PPTX
Chapter - 2.pptx
MikialeTesfamariam
 
PDF
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
ODP
Python slide.1
Aswin Krishnamoorthy
 
PPTX
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
PPT
Strings Arrays
phanleson
 
PPTX
11 Introduction to lists.pptx
ssuser8e50d8
 
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
PPT
Data types usually used in python for coding
PriyankaRajaboina
 
PPT
02python.ppt
ssuser492e7f
 
PPT
02python.ppt
rehanafarheenece
 
PPTX
009 Data Handling class 11 -converted.pptx
adityakumar123456112
 
PPTX
009 Data Handling class 11 -converted.pptx
adityakumar123456112
 
PDF
Python data handling
Prof. Dr. K. Adisesha
 
PPTX
009 Data Handling .pptx
ssuser6c66f3
 
PPTX
Basic data types in python
sunilchute1
 
PPT
Python programming unit 2 -Slides-3.ppt
geethar79
 
Python Session - 3
AnirudhaGaikwad4
 
Introduction To Programming with Python-3
Syed Farjad Zia Zaidi
 
PRESENTATION ON STRING, LISTS AND TUPLES IN PYTHON.pptx
kirtisharma7537
 
PPS_Unit 4.ppt
KundanBhatkar
 
Chapter - 2.pptx
MikialeTesfamariam
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
Python slide.1
Aswin Krishnamoorthy
 
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Strings Arrays
phanleson
 
11 Introduction to lists.pptx
ssuser8e50d8
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Data types usually used in python for coding
PriyankaRajaboina
 
02python.ppt
ssuser492e7f
 
02python.ppt
rehanafarheenece
 
009 Data Handling class 11 -converted.pptx
adityakumar123456112
 
009 Data Handling class 11 -converted.pptx
adityakumar123456112
 
Python data handling
Prof. Dr. K. Adisesha
 
009 Data Handling .pptx
ssuser6c66f3
 
Basic data types in python
sunilchute1
 
Python programming unit 2 -Slides-3.ppt
geethar79
 
Ad

Recently uploaded (20)

PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Doc9.....................................
SofiaCollazos
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Software Development Methodologies in 2025
KodekX
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 

Python Datatypes by SujithKumar

  • 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