Python Module 2
Python Module 2
in Python
•
•
Module 2 COMPOUND DATA
TYPES: STRINGS, LISTS,
TUPLES - declaration, Built
in functions.
DICTIONARIES: Concept
of dictionary, techniques to
create, update & delete
dictionary items. .
Strings are amongst the most popular types in python.
strings
Python treats single quotes the same as double quotes.
For example −
• To access substrings, use the square brackets for slicing along with the index or indices to
obtain a substring.
For example −
var1[0]: H
var2[1:5]: ytho
Updating Strings
For example −
var1 = 'Hello World!‘
print ("Updated String :- ", var1[:6] + 'Python')
Assume string
variable a holds 'Hello'
and variable b holds
'Python', then −
String Formatting Operator
• The syntax for triple quotes consists of three consecutive single or double quotes.
For example—
”””
print (para_str)
* Note how every single special character has been converted to its printed form,
right down to the last NEWLINE at the end of the string between the "up." and closing
triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at
the end of a line or its escape code (\n) −
Unicode String
• Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-
bit Unicode.
• This allows for a more varied set of characters, including special characters from most languages in
the world.
For example--
print u'Hello, world!'
--When the above code is executed, it produces the
following result −
Hello, world!
2. Center(width, fillchar):- Returns a space-padded string with the original string centered to a
total of width columns.
Syntax
str.center(width[, fillchar])
Example
str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(40, 'a'))
3. count(beg = 0, end = len(string)):- Counts how many times str occurs in
string or in a substring of string if starting index beg and ending index end
are given.
Syntax
str.count(sub, start= 0,end=len(string))
example
str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(sub))
sub = 'exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))
example
str = "this“ # No space & digit in this string
print (str.isalpha())
str = "this is string example....wow!!!"
print (str.isalpha())
8. isdigit():- Returns true if string contains only digits and false
otherwise.
Syntax
str.isdigit()
example
str = "123456“ # Only digit in this string
print (str.isdigit())
str = "this is string example....wow!!!"
print (str.isdigit())
9. islower() :-Returns true if string has at least 1 cased character and all
cased characters are in lowercase and false otherwise.
Syntax
str.islower()
example
str = "THIS is string example....wow!!!"
print (str.islower())
str = "this is string example....wow!!!"
print (str.islower())
example
str = "This Is String Example...Wow!!!
print (str.istitle())
str = "This is string example....wow!!!"
print (str.istitle())
13. isupper():-Returns true if string has at least one cased character and
all cased characters are in uppercase and false otherwise.
Syntax
str.isupper()
example
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())
str = "THIS is string example....wow!!!"
print (str.isupper())
14. join(seq):- Merges (concatenates) the string representations of
elements in sequence seq into a string, with separator string.
Syntax
str.join(sequence)
example
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))
15. len(string):- Returns the length of the string
Syntax
len( str )
example
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
example
str = "this is string example....wow!!!"
print str.ljust(50, '0')
17. lower():- Converts all uppercase letters in string to lowercase.
Syntax
str.lower()
example
str = "THIS IS STRING EXAMPLE....WOW!!!"
print str.lower()
example
str = " this is string example....wow!!! "
print str.lstrip()
str = "88888888this is string example....wow!!!8888888"
print (str.lstrip('8’))
19. max(str):- Returns the max alphabetical character from the string
str.
Syntax
max(str)
example
str = "this is really a string example....wow!!!"
print "Max character: " + max(str)
str = "this is a string example....wow!!!"
print "Max character: " + max(str)
20. min(str):- Returns the min alphabetical character from the string str.
Syntax
min(str)
example
str = "www.google.com"
print ("Min character: " + min(str))
str = "GOOGLE"
print ("Min character: " + min(str))
21. replace(old, new [, max]):- Replaces all occurrences of old in string with
new or at most max occurrences if max given.
Syntax
str.replace(old, new[, max])
example
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 2))
example
str1 = "this is string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.index(str2))
example
str = "this is string example....wow!!!"
print str.rjust(50, '0')
25. rstrip():- Removes all trailing whitespace of string.
Syntax
str.rstrip([chars])
example
str = " this is string example....wow!!! "
print (str.rstrip())
str = "88888888this is string example....wow!!!8888888"
print (str.rstrip('8’))
example
str = "this is \nstring example....\nwow!!!"
print (str.splitlines( ))
example
str = "this is string example....wow!!!"
print str.startswith( 'this' )
print str.startswith( 'is', 2, 4 )
print str.startswith( 'this', 2, 4 )
29. strip([chars]):- Performs both lstrip() and rstrip() on string
Syntax
str.strip([chars])
example
str = "0000000this is string example....wow!!!0000000"
print (str.strip( '0’ ))
example
str = "this is string example....wow!!!"
print (str.swapcase())
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.swapcase())
31. title():- Returns "titlecased" version of string, that is, all words begin
with uppercase and the rest are lowercase.
Syntax
str.title()
example
str = "this is string example....wow!!!"
print (str.title())
example
str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.upper())
33. zfill (width):- Returns original string left padded with zeros to a total
of width characters;
Syntax
str.zfill(width)
example
str = "this is string example....wow!!!"
print (str.zfill(40))
print (str.zfill(50))
Membership operation
>>> 3 in [1, 2, 3]
True
Iteration operation
>>>for x in [1,2,3]:
print x
1
2
3
Length of the list
>>>len([1, 2, 3])
3
The + Operator
The + operator produces a new list whose
value is the concatenation of its arguments.
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
The * Operator
The * operator produces a new list that
“repeats” the original content.
>>> [1, 2, 3] * 3
1, 2, 3, 1, 2, 3, 1, 2, 3]
Deleting List Elements
To remove a list element, we can use either the del statement if we know
exactly which element(s) we are deleting or the remove() method if we do
not know.
For example −
Using del statement----uses index value
>>> list = ['physics', 'chemistry', 1997, 2000]
>>> del list[2]
>>> print list
['physics', 'chemistry', 2000]
using remove()----element as parameter
>>> list = ['physics', 'chemistry', 1997, 2000]
>>> list.remove(2000)
>>> print list
['physics', 'chemistry', 1997]
Accessing list elements
>>>L[1:2]
'Spam‘ #Slicing fetches sections
>>>L[0:]
'spam', 'Spam', 'SPAM!'
Methods
>>> li = [1, 11, 3, 4, 5]
Potentially confusing:
◦ extend takes a list as an argument.
◦ append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Lists have many methods, including index, count, remove, reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
>>> li = [5, 2, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
>>> li = [5, 2, 6, 8]
insert(i,x)
>>> li.insert(3,4)
>>> li
[5,2,6,4,8]
remove(x)
>>> li.remove(6)
>>> li
[5,2,4,8]
pop([i]), pop()
>>> li.pop(3)
>>>li
[5,2,6,8]
max(list) Returns item from the list with max value.
>>> li=[1,56,72,'a']
>>> max(li)
'a‘
Syntax
cmp(list1, list2)
Parameters
list1 − This is the first list to be compared.
list2 − This is the second list to be compared.
Return Value
1 if list1 is bigger than list2
-1 if list2 is bigger than list1
0 if both lists are equal
Python Tuples
1. A tuple is a sequence of immutable Python objects.
2. Tuples are sequences, just like lists.
3. The differences between tuples and lists are,tuples cannot be changed unlike
lists. Tuples use parentheses, whereas lists use square brackets.
4. Creating a tuple is as simple as putting different comma-separated values.
5. Optionally we can put these comma-separated values between parentheses
also.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The empty tuple is wri en as two parentheses containing nothing −
tup1 = ()
To write a tuple containing a single value we have to include a comma,
even though there is only one value −
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Accessing Values in Tuples:
To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain value available at that index.
For example −
>>>tup1 = ('physics', 'chemistry', 1997, 2000)
>>>tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>>print ("tup1[0]: ", tup1[0])
tup1[0]: physics
>>>print ("tup2[1:5]: ", tup2[1:5])
>>>tup2[1:5]
(2, 3, 4, 5)
Updating Tuples
Tuples are immutable.
which means we cannot update or change the values of tuple elements.
We can take portions of existing tuples to create new tuples as the following
example demonstrates −
>>>tup1 = (12, 34.56)
>>>tup2 = ('abc', 'xyz')
>>> tup1[1]='a'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tup1[1]='a'
TypeError: 'tuple' object does not support item assignment
>>>tup3 = tup1 + tup2
>>>print (tup3)
(12, 34.56, 'abc', 'xyz')
Deleting Tuple Elements
Removing individual tuple elements is not possible.
To explicitly remove an entire tuple, just use
the del statement.
For example:
>>>tup = ('physics', 'chemistry', 1997, 2000)
>>>print (tup)
('physics', 'chemistry', 1997, 2000)
>>>del tup
>>>print ("After deleting tup : "),print (tup)
Note an exception raised, this is because after del tup tuple does
not exist any more −
Basic Tuples 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.
Operations on tuples
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way
for tuples as they do for strings.
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying
symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples
>>> li='a','c'
>>> type(li)
<class 'tuple'>
Built-in Tuple Functions
2. A dictionary key can be almost any Python type, but are usually numbers or strings.
4. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
For example −
>>>dict = {}
>>>print (dict)
For example −
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>print ("dict['Name']: ", dict['Name'])
dict['Name']: Zara
>>>print ("dict['Age']: ", dict['Age'])
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the
dictionary it raises an error
For example—
For example--
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>dict['Age'] = 8 # Update existing entry
>>>dict['School'] = "DPS School" # Add new entry
>>>print ("dict['Age']: ", dict['Age'])
dict['Age']: 8
>>>print ("dict['School']: ", dict['School'])
dict['School']: DPS School
Delete Dictionary Elements
• We can either remove individual dictionary elements
For example −
{}
dict['Age']:
Note:-an exception is raised because, after del dict, dictionary does not exist any more −
Properties of Dictionary Keys
• Dictionary values have no restrictions.
• They can be any arbitrary Python object, either standard objects or user-defined objects.
• Same is not true for the keys.
(a) More than one entry per key is not allowed. Which means no duplicate key is allowed. When
duplicate keys are encountered during assignment, the last assignment wins.
For example--
>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': ‘Anna'}
>>>print ("dict['Name']: ", dict['Name'])
dict['Name']: Anna
(b) Keys must be immutable. Which means you can use strings, numbers
or tuples as dictionary keys but something like ['key'] is not allowed.
For example--
>>>dict = {['Name']: 'Zara', 'Age': 7}
>>>print ("dict['Name']: ", dict['Name'])
1. Python dictionary cmp() Method :- The method cmp() compares two dictionaries based on key and values.
Syntax
cmp(dict1, dict2)
Parameters
dict1 -- This is the first dictionary to be compared with dict2.
dict2 -- This is the second dictionary to be compared with dict1.
Return Value
This method returns 0 if both dictionaries are equal,
-1 if dict1 < dict2 and
1 if dict1 > dict2.
For Example
>>>dict1 = {'Name': 'Zara', 'Age': 7}
>>>dict2 = {'Name': 'Mahnaz', 'Age': 27}
>>>dict3 = {'Name': 'Abid', 'Age': 27}
>>>dict4 = {'Name': 'Zara', 'Age': 7}
>>>print ("Return Value : %d" % cmp (dict1, dict2))
Return Value : -1
>>>print ("Return Value : %d" % cmp (dict2, dict3))
Return Value : 1
>>>print ("Return Value : %d" % cmp (dict1, dict4))
Return Value : 0
2. Python dictionary len() Method :- The method len() gives the total length of the
dictionary. This would be equal to the number of items in the dictionary.
Syntax
len(dict)
Parameters
dict -- This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
For Example--
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Length : %d" % len (dict))
Length : 2
3. Python dictionary str() Method :- The method str() produces a printable string
representation of a dictionary.
Syntax
str(dict)
Parameters
dict -- This is the dictionary.
Return Value
This method returns string representation.
Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Equivalent String : %s" % str (dict))
Equivalent String : {'Age': 7, 'Name': 'Zara'}
4. Python dictionary type() Method :- The method type() returns the type of the
passed variable. If passed variable is dictionary then it would return a dictionary
type.
Syntax
type(dict)
Parameters
dict -- This is the dictionary.
Return Value
This method returns the type of the passed variable.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Variable Type : %s" % type (dict))
Variable Type : <type 'dict'>
5. Python dictionary clear() Method :- The method clear() removes all items from the dictionary.
Syntax
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Start Len : %d" % len(dict))
Start Len : 2
>>>dict.clear()
>>>print ("End Len : %d" % len(dict))
End Len : 0
6. Python dictionary copy() Method :- The method copy() returns a shallow copy of
the dictionary.
Syntax
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
For Example
>>>dict1 = {'Name': 'Zara', 'Age': 7}
>>>dict2 = dict1.copy()
>>>print ("New Dictinary : %s" % str(dict2))
New Dictinary : {'Name': 'Zara', 'Age': 7}
By "shallow copying" it means the content of the dictionary is not copied by value, but just
creating a new reference.
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
Syntax
dict.fromkeys(seq[, value])
Parameters
seq -- This is the list of values which would be used for dictionary keys
preparation.
value -- This is optional, if provided then value would be set to this value
Return Value
This method returns the list.
Example
>>>seq = ('name', 'age', 'sex')
>>>dict = dict.fromkeys(seq)
>>>print ("New Dictionary : %s" % str(dict))
New Dictionary : {'age': None, 'name': None, 'sex': None}
Syntax
dict.get(key, default=None)
Parameters
key -- This is the Key to be searched in the dictionary.
default -- This is the Value to be returned in case key does not exist.
Return Value
This method return a value for the given key. If key is not available, then returns default value None.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.get('Age'))
Value : 7
>>>print ("Value : %s" % dict.get('Education', "Never"))
Value : Never
9. Python dictionary has_key() Method :- The method has_key() returns true if a given key is available
in the dictionary, otherwise it returns a false.
Syntax
dict.has_key(key)
Parameters
key -- This is the Key to be searched in the dictionary.
Return Value
This method return true if a given key is available in the dictionary, otherwise it returns a false.
Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.has_key('Age'))
Value : True
>>>print ("Value : %s" % dict.has_key('Sex'))
Value : False
10. Python dictionary items() Method :- The method items() returns a list of dict's
(key, value) tuple pairs
Syntax
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.items())
Value : dict_items([('Name', 'Zara'), ('Age', 7)])
11. Python dictionary keys() Method :- The method keys() returns a list of all the
available keys in the dictionary.
Syntax
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.keys())
Value : dict_keys(['Name', 'Age'])
12. Python dictionary setdefault() Method :- The method setdefault() is similar to
Syntax
dict.setdefault(key, default=None)
Parameters
Return Value
This method returns the key value available in the dictionary and if given key is not available then it will return provided default
value.
For Example
Value : 7
Value : None
13. Python dictionary update() Method :- The method update() adds dictionary dict2's key-values pairs
in to dict. This function does not return anything.
Syntax
dict.update(dict2)
Parameters
dict2 -- This is the dictionary to be added into dict.
Return Value
This method does not return any value.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>dict2 = {'Sex': 'female' }
>>>dict.update(dict2)
>>>print ("Value : %s" % dict)
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
14. Python dictionary values() Method :- The method values() returns a list of all the
values available in a given dictionary.
Syntax
dict.values()
Parameters
NA
Return Value
This method returns a list of all the values available in a given dictionary.
For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.values())
Value : [7, 'Zara']