33
PYHTON DATA TYPES Session-2

Python Datatypes by SujithKumar

Embed Size (px)

DESCRIPTION

This Power Point Presentation explains the what are the data types present in Python and each data type has one sample code

Citation preview

Page 1: Python Datatypes by SujithKumar

PYHTON DATA TYPESSession-2

Page 2: Python Datatypes by SujithKumar

Mutable Vs Immutable ObjectsIn 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 Objectsbyte arraylistsetdict

int, float, long, complex

strtuplefrozen set

Page 3: Python Datatypes by SujithKumar

Python Data Types Python´s built-in (or standard) data types can be grouped into several classes.

Boolean TypesNumeric Types Sequences Sets Mappings

Page 4: Python Datatypes by SujithKumar

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:

Page 5: Python Datatypes by SujithKumar

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)

Page 6: Python Datatypes by SujithKumar

IntegersExamples: 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 integersExample: 999999999999999999999L Must end in either l or L Can be arbitrarily long

Page 7: Python Datatypes by SujithKumar

Floating point numbersExamples: 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

Page 8: Python Datatypes by SujithKumar

Octal constantsExamples: 0177, -01234 Must start with a leading ‘0’

Hex constantsExamples: 0x9ff, 0X7AE Must start with a leading ‘0x’ or ‘0X’

Complex numbersExamples: 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

Page 9: Python Datatypes by SujithKumar

Sequences There are five sequence types

1) Strings

2) Lists

3) Tuple

4) Bytearray

5) Xrange

Page 10: Python Datatypes by SujithKumar

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”

Page 11: Python Datatypes by SujithKumar

Concatenation and repetitionStrings are concatenated with the + sign:

>>> 'abc'+'def''abcdef'

Strings are repeated with the * sign:>>> 'abc'*3'abcabcabc'

Page 12: Python Datatypes by SujithKumar

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'

Page 13: Python Datatypes by SujithKumar

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.

Page 14: Python Datatypes by SujithKumar

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()

Page 15: Python Datatypes by SujithKumar

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()

Page 16: Python Datatypes by SujithKumar

Output for the string methods sample code

Page 17: Python Datatypes by SujithKumar

2) ListsLists 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 = []

Page 18: Python Datatypes by SujithKumar

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

Page 19: Python Datatypes by SujithKumar

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

Page 20: Python Datatypes by SujithKumar

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])

Page 21: Python Datatypes by SujithKumar

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]

Page 22: Python Datatypes by SujithKumar

Output for the list methods sample code

Page 23: Python Datatypes by SujithKumar

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 = ()

Page 24: Python Datatypes by SujithKumar

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

Page 25: Python Datatypes by SujithKumar

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.

Page 26: Python Datatypes by SujithKumar

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.

Page 27: Python Datatypes by SujithKumar

SetsThe 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.

Page 28: Python Datatypes by SujithKumar

Sets Operations

Operation Equivalent Resultlen(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 | tnew set with elements from

both s and t

s.intersection(t) s & tnew set with elements common

to s and t

s.difference(t) s - tnew 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

Page 29: Python Datatypes by SujithKumar

Operation Equivalent Result

s.update(t) s |= treturn 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 -= treturn 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

Page 30: Python Datatypes by SujithKumar

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 bracesKeys 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}

Page 31: Python Datatypes by SujithKumar

Some of the dictionary methods listed in belowlen( dict )

dict.copy( )

dict.items( )

dict.keys( )

dict.values( )

dict.has_key(‘key’)

viewitems( )

viewkeys( )

viewvalues( )

Page 32: Python Datatypes by SujithKumar

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')

Page 33: Python Datatypes by SujithKumar

Output for the dictionary sample code