The document describes the differences between mutable and immutable objects in Python, categorizing data types into groups such as boolean, numeric, sequences, sets, and mappings. It elaborates on specific data types like integers, floats, lists, tuples, bytearrays, and dictionaries, detailing their properties, operations, and sample methods. Additionally, it explains how to manipulate these data types through operations like indexing, concatenation, and various built-in methods.
Mutable Vs ImmutableObjects 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´sbuilt-in (or standard) data types can be grouped into several classes. Boolean Types Numeric Types Sequences Sets Mappings
4.
Boolean Types: The typeof 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 supportsfour 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
1. Strings: Stringsin 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 Stringsare 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 everykth 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 thestring 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 forString 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()
2) Lists Lists arepositionally 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 indexingworks 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 Listsrespond 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 theList 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 forList 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]
3) Tuple: Atuple 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 Tuplesrespond 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 xrangetype 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 moduleprovides 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 EquivalentResult 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 Amapping 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 thedictionary methods listed in below len( dict ) dict.copy( ) dict.items( ) dict.keys( ) dict.values( ) dict.has_key(‘key’) viewitems( ) viewkeys( ) viewvalues( )
32.
Sample code fordictionary 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')