Python Dictionary introduction : Python Tutorial : Part 11

Python Dictionary: Introduction:


In this tutorial, we will discuss Python dictionary and some built-in methods. A dictionary is a collection of (key: value) paired items. All elements of a dictionary are placed inside curly braces { }, each element is separated by a comma. The elements of a dictionary are unordered and using a key, we can get a value.
All keys should be unique in a dictionary and should be of immutable data types. 

Create a Python dictionary:

We can create a dictionary in python using curly braces directly or by using dict() method. 
dict1 = { "one":1 , "two":2 ,"three":3 }
print dict1 #{'three': 3, 'two': 2, 'one': 1}

dict2 = {}
print dict2 # {}

dict3 = dict({"one":1 ,"two":2 ,"three":3 })
print dict3 # {'one': 1, 'three': 3, 'two': 2}

dict4 = dict([("one",1),("two",2),("three",3)])
print dict4 # {'three': 3, 'two': 2, 'one': 1}
In the above example, dict2 is an empty dictionary.

Access an element of a python dictionary:

Since keys are unique, using a key we can get the value of a dictionary element.Using a square bracket, and passing the key, we can get the value for that key. If the key is not in the dictionary, it will throw a key error. We can also use get() instead of using a square bracket. get() doesn’t throw any key error.
dict1 = { "one" : 1, "two" : 2, "three" : 3, "four" : 4}
print dict1["one"] # 1

# print dict1["five"] #key error

print dict1.get("four") # 4

print dict1.get("five") # Prints None

Updating and Deleting dictionary elements: 

Python dictionary is mutable. We can add or update a value inside a dictionary. Using the key, we can update its value or we can add a whole key-value pair to a dictionary as shown below:
dict1 = { "one" : 1, "two" : 2, "three" : 3, "four" : 4}
print dict1 # {'four': 4, 'three': 3, 'two': 2, 'one': 1}

dict1["four"] = 4.0
print dict1 # {'four': 4.0, 'three': 3, 'two': 2, 'one': 1}

dict1["five"] = 5
print dict1 # {'four': 4.0, 'three': 3, 'five': 5, 'two': 2, 'one': 1}

To delete an element of a dictionary:

We can delete a specific item of a dictionary or we can delete the complete dictionary. ‘del()’ statement is used mainly for this. Also, ‘clear()’ and ‘pop()’ can be used. ‘pop()’ returns the element that is removed and clear() removes all elements of a dictionary.
dict1 = { "one" : 1, "two" : 2, "three" : 3, "four" : 4}
print dict1 # {'four': 4, 'three': 3, 'two': 2, 'one': 1}

del dict1["four"]
print dict1 # {'three': 3, 'two': 2, 'one': 1}

print dict1.pop("three") # 3

print dict1 # {'two': 2, 'one': 1}

dict1.clear()
print dict1 # {}

del dict1
print dict1 # Name error will be thrown

Iterating through a python dictionary: 

Using a for loop, we can iterate through a python dictionary. 
dict1 = { "one" : 1, "two" : 2, "three" : 3, "four" : 4}
 
for i in dict1 :
    print dict1[i]
The above program will print all values of the dictionary dict1.
That’s all for python dictionary. In our next tutorial, we will check different commonly used dictionary methods.

Python set and built in methods : Python tutorial : Part 10

Python Set:


Python Set Introduction : Introduced in python 2.4, Python set is a unordered collection of unique immutable elements. The elements of a set can be anything: numbers, characters, alphabet, other sets etc. A set can be changed. We can add or remove items. We can also perform set operations like differences, intersections etc. between sets.

 
Creating a Set:
 
We can create a Set using the built-in set() function or using curly braces. curly braces were introduced in python 2.6.
 

Using set() function :

 

set1 = set([1,2,3,4,5])
print set1 # set([1, 2, 3, 4, 5])
 
set2 = set((1,2,3,4,5,4,3,2,1))
print set2 # set([1, 2, 3, 4, 5])
 
set3 = set("codevscolor")
print set3 # set(['c', 'e', 'd', 'l', 'o', 's', 'r', 'v’])
 
set4 = set(("one","two","three"))
print set4 # set(['three', 'two', 'one'])
In the first example, we have passed a list of numbers to the set() function. In the second example, we have passed a tuple with repeating numbers. But you can see that the same numbers are removed from the set. In the third one, a string is passed. We can also pass specific elements to a python set, as shown in the last example.
 
All these elements we have used in the above examples are immutable. If you try to use a mutable element as a child of a set, it will throw an error.
 
Let’s try with curly braces to create a set :
set1 = {1,2,3,4,5}
print set1 # set([1, 2, 3, 4, 5])
 
set2 = {1,2,3,4,5,4,3,2,1}
print set2 # set([1, 2, 3, 4, 5])
 
set3 = {"codevscolor"}
print set3 # set(['codevscolor'])
 
set4 = {"one","two","three"}
print set4 # set(['three', 'two', 'one'])
 
Creating an empty set :

We have seen two different ways to create set in python. So, how to create an empty set ? We can use {} and set() , both . But which one to use ? Let’s check :

set1 = {}
print type(set1) # <type 'dict'>
 
set2 = set()
print type(set2) # <type 'set'>
That means, only way to create an empty set is to use the set() method. {} creates an empty dictionary.
 
Frozensets :
Sets cannot contain any mutable elements, but sets are mutable. Frozensets are similar to sets but they are immutable, i.e. you cannot change a frozenset.
set0 = set((1,2,3,4,5))
print set0 # set([1, 2, 3, 4, 5])
 
set0.add("element")
print set0 # set([1, 2, 3, 4, 5, 'element'])
 
set1 = frozenset((1,2,3,4,5))
print set1 # frozenset([1, 2, 3, 4, 5])
 
set1.add("element") # AttributeError: 'frozenset' object has no attribute 'add'
Adding elements to a python set :
We can add a single element using add() method , or multiple elements using update() method. Let’s check :
set1 = {1,2,3,4}
print set1 # set([1, 2, 3, 4])
 
set1.add(5)
print set1 # set([1, 2, 3, 4, 5])
 
set1.update({"and"},[6,7,8],{9,10,11})
print set1 # set(['and', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
So, you can see that the update methods can take more than one argument. The argument can be a tuple, list, string or an another python set.
 
Removing elements from a python set:
We can use discard(element) or remove(element) to remote any set member. In the case of discard, if “element” is not a member of a set, nothing will be done. But, in case of remove(element), it will throw a KeyError.
set1 = {1,2,3,4}
print set1 # set([1, 2, 3, 4])
 
set1.discard(3)
print set1 # set([1, 2, 4])
 
set1.discard(3) #no error
 
set1.remove(4)
print set1 # set([1, 2])
 
set1.remove(4) # KeyError
We have two more methods for removing elements in a python set : pop() and clear().

pop() will remove a random element and return it. clear() will remove all elements of a set.

 

set1 = {1,2,3,4,5,6}
print set1 # set([1, 2, 3, 4, 5, 6])
 
el = set1.pop()
print el # 1
 
set1.add(el)
print set1 # set([1, 2, 3, 4, 5, 6])
 
el2 = set1.pop()
print el2# 2
You can see that both times a different element is popped out for the same set.
set1 = {1,2,3,4,5}
 
print set1 # set([1, 2, 3, 4, 5])
 
set1.clear()
 
print set1 # set([])
Python set union and intersection():
Union of two set is the set of all elements from both sets. An intersection of two set is the set of all common elements between these two sets.
for union , we use union() or ‘|’ operator. For intersection, we use intersection() or ‘&’ operator.
set1 = {1, 2, 3, 4}
set2 = {5, 4, 3, 2}
 
 
print set1.union(set2) # set([1, 2, 3, 4, 5])
print ( set1 | set2 ) # set([1, 2, 3, 4, 5])
 
 
print set1.intersection(set2 # set([2, 3, 4])
print (set1 & set2) # set([2, 3, 4])
 
Set difference and symmetric difference:
For two sets set1 and set2, difference is the elements that are only in set1 but not in set2. Symmetric difference between two sets set1 and set2 is the set of elements of both set1 and set2 except common elements.
 
To find the difference between two sets, we use “difference()” or “-“ operator. For symmetric difference, we use “symmetric_difference” or “^” operator.
set1 = {1, 2, 3, 4}
set2 = {5, 4, 3, 2}
 
print set1.difference(set2) # set([1])
print set1 - set2 # set([1])
 
 
print set1.symmetric_difference(set2) # set([1, 5])
print set1 ^ set2 # set([1, 5])
 
Subset and superset check:
set1.issubset(set2) returns True , if set1 is a subset of set2. Similarly, set1.issuperset(set2) returns True if set1 is a superset of set2. We can also use “<=“ for “Subset of” and “>=“ for superset of .
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
 
print set1.issubset(set2)
print (set1 <= set2)
 
print set2.issuperset(set1)
print (set2 >= set1)
All print statements will return “True”.
 
 
 

Python Tutorial : Part 9 : Common Python String Methods

Common Python String Methods: 
In this tutorial, we will check some popular python String methods and their uses:

1. capitalize():
It capitalizes the first letter of a python String.
str1 = "hello World !!"
print str1.capitalize()
Output: “Hello World !!”
2. count (sub_string_name , starting_index, ending_index ) :
This method will check how many time a substring appears in a string within range starting_index and ending_index.
str1 = "hello hello World !!"
subStr1 = "hello"
print str1.count(subStr1,0,len(str1))
The output will be 2

3. endswith(suffix,starting_index,ending_index) :
Find if the string ends with “suffix” within range starting_index and ending_index
str1 = "hello hello World !!"

suffix1 = "!!"
suffix2 = "world"

print str1.endswith(suffix1,0,len(str1))
print str1.endswith(suffix2,0,len(str1))

Output will be True for the first print, and False for the second one.

 

4. find(str,starting_index,ending_index):
Find a string ‘str’ inside a string within index range “starting_index” and “ending_index”. Return the index position, if the string is found. Return -1 otherwise.
str1 = "hello World !!"

str2 = "!!"

print str1.find(str2,0,len(str1))

The result will be ’12


5. isalpha(), isdigit() and isalnum() :
isalpha(): returns True if a python string has all alphabetic characters and it is not empty.It should not contain any space or other characters.

isdigit(): returns True if a python string contains all digits and it is not empty.It should not contain any space or other characters.

isalnum(): returns True if a python string has all alphanumeric characters and it is not empty.It should not contain any space or other characters.
str1 = "abcdefg"
str2 = "1234567"
str3 = "abcd1234"
str4 = ""


print str1.isalpha() #True
print str2.isalpha()
print str3.isalpha()
print str4.isalpha()

print str1.isdigit()
print str2.isdigit() #True
print str3.isdigit()
print str4.isdigit()

print str1.isalnum() #True
print str2.isalnum() #True
print str3.isalnum() #True
print str4.isalnum()


6. islower() and isupper() :
islower() : Returns True if a string is non-empty and all characters are in lowercase.

isupper() : Returns True if a string is non-empty and all characters are in uppercase.

str1 = "abcdefg"
str2 = "ABCDEF"
str3 = "ABC DEF"

print str1.islower()
print str2.isupper()
print str3.isupper()
print str3.islower()
Output will be:

True
True
True
False
7. lower() and upper() :
lower():
Convert all character of a python string to lowercase

upper():
Convert all character of a python string to uppercase
str1 = "Hello World !!"

print str1.upper()
print str1.lower()
output :
HELLO WORLD !!
hello world !!
8. len(string) ,max(string) , min(string) :
len(string) : Returns the length of a string
max(string) : Returns the max alphabetical character
min(string) : Returns the min alphabetical character 

str1 = "HelloWorld!!"

print len(str1)
print max(str1)
print min(str1)
output : 
12
r
!
9. lstrip() and rstrip() :
lstrip() : Removes all leading whitespace
rstrip() : Remove all trailing whitespace
str1 = " Hello World "

print "="+str1.lstrip()+"="
print "="+str1.rstrip()+"="
Output :
=Hello World =
= Hello World=
10. replace( old , new , limit ):
replace a substring ‘old’ with ‘new‘. ‘limit’ is optional. It decides how many replacements should be done.
str1 = "new new new new new new new new"
 
print str1.replace('new','old')
print str1.replace('new','old',3)
output :
old old old old old old old old
old old old new new new new new
11. startswith(sub_string, beginning_index, end_index) :
Return True if a string starts with a substring “sub_string”and the range of index for the string is “beginning_index” and “end_index”.
str1 = "Hello World !!"
 
print str1.startswith("Hello",0,len(str1))
it will return True.
12. swapcase() and title() :
swapcase() : invert case of all letter in a string.
title() : convert all words start with uppercase.
str1 = "Hello worlD !!"
 
print str1.swapcase()
print str1.title()
Output : 
hELLO WORLd !!
Hello World !!
13. split() :
Split takes two arguments: First one decides on which separator, the string should be split .The second one decides a maximum number of the split. The second parameter is optional.
It returns a list of all substrings.
str1 = "Hello : World !! : Hello : World"
 
print str1.split()
print str1.split(':')
print str1.split(':',1)
Output will be : 
['Hello', ':', 'World', '!!', ':', 'Hello', ':', 'World']
['Hello ', ' World !! ', ' Hello ', ' World']
['Hello ', ' World !! : Hello : World’]

Python tutorial : Part 8 : Python String

Python String:

To create a String in python, we use a single quote or double quotes. Enclosing characters inside quotes creates a string. Following example will show you to create a python string :

string1 = 'using single quote'
string2 = "using double quotes"

print string1
print string2

The above program will print both of the strings.

Triple Quotes:
With triple quotes, we can write multiline strings in python. It can contain a newline character, tab or any other special characters.

string1 = """This is a \n multiline string with a tab (\t) here."""
string2 ='''This is also a multiline
string'''

print string1
print string2
This program will give the following output: 
This is a
 multiline string with a tab () here.
This is also a multiline
string
Escape Sequence:
An escape sequence is interpreted differently and it starts with a backslash ( \ ).  Following are the list of all escape sequence used in python:
\newline
Backslash and newline ignored
\b
Backspace
\’
Single quote
\”
Double quote
\a
\e
\s
Alert/Bell
escape
space
\\
Backslash
\t
Tab
\v
Vertical Tab
\r
Carriage Return
\f
Formfeed
\n
New Line
\nnn
octal notation
\xnn
hexadecimal notation
Raw Strings:
Normally, backslash ( \ ) is considered as a special character. To ignore it, we can use raw string. A raw string is defined as r’string’.
string1 = "not ignoring\tbackslash"
string2 = r"ignoring\tbackslash"

print string1
print string2
Output will be:
not ignoringbackslash
ignoring\tbackslash
Accessing Values in a String:

Accessing a character is same as accessing elements in lists and tuples. We can use index inside a square bracket for a particular position. For accessing a substring, we can use slicing like string_name[ start: end ]. If start is ‘0’ and end is ‘4′, we will get the substring starting from 0th position up to the 4th position of the string.

Negative indexing is also possible in python strings. If we use ‘-1’ as an index, it will point to the last character, similarly ‘-2’ for the second last and so on.

The following example will clarify your doubt:

string1 = "Hello World!!"

print string1[0] # output : 'H'
print string1[-1] # output : '!'
print string1[0:5] # output : 'Hello'
print string1[5:-1] # output : ' World!’

If we try to use an invalid index, it will throw IndexError.


Updating a String: 

Strings are immutable i.e. we cannot change or delete any character of a string. Instead, we can create a different String.

e.g. change the string “hello world!!” to “hello universe!!”. Since we cannot change any character, instead we can use slicing operation as shown above to create a different string:

string1 = "Hello World!!"
string2 = string1[0:6]+"universe"+string1[-2:]

print string2


Python String Operations:

Concatenation :
The plus ( + ) operator is used to concatenate two strings. 
If we put two strings together, without any + sign, they will concatenate
Two strings on a different line, enclosed in a bracket ( ) will concatenate.

e.g. :

string1 = "Hello" " World!!"
print string1

string2 = ( "Hello"  " World!!")
print string2

string3 ="Hello"

string4 =" World!!"
print string3 + string4

In the example above, all the print statements will give the same output: “Hello World!!”

Repeating Strings:

Using pointer ‘*’ operator, we can repeat a string ’n’ no. of times.

string1 = "Hello "
print string1*3 # prints Hello Hello Hello
MemberShip Check:

Using ‘in’ and ‘not in’, we can check if a character exists in a string. It returns ’True’ if true, ‘False’ otherwise.

string1 = "Hello World!!"

print 'H' in string1 # True
print 'H' not in string1 # False
Formatting String :

Python has string format operator % to format string :

print "Character %c , String %s and a number %d " %('a','Apple',34)
Output :
Character a, String Apple and a number 34

Following are the list of symbols and the meaning of each symbol:

 

d
Signed integer decimal.
i
Signed integer decimal.
o
Unsigned octal.
u
Unsigned decimal.
x
Unsigned hexadecimal (lowercase).
X
Unsigned hexadecimal (uppercase).
e
Floating point exponential format (lowercase).
E
Floating point exponential format (uppercase).
f
Floating point decimal format.
F
Floating point decimal format.
g
Same as “e” if the exponent is greater than -4 or less than precision, “f” otherwise.
G
Same as “E” if the exponent is greater than -4 or less than precision, “F” otherwise.
c
Single character (accepts integer or single character string).
r
String (converts any python object using repr()).
s
String (converts any python object using str()).
%
No argument is converted results in a “%” character in the result.
format() for Formatting String :
We can also use format() to format a String in python. Curly bracket is used as a replacement.
print "Formatting {}, {}, {}".format('a','b','c')
print "Formatting {2}, {1}, {0}".format('a','b','c')
print "Formatting {c}, {b}, {a}".format(a='apple',b='ball',c='cat')
The output will be:
Formatting a, b, c
Formatting c, b, a
Formatting cat, ball, apple

 

Python Tutorial : Part 7 : python tuple

Python tuple:
Python tuple is same as python list but it is immutable. We cannot change a tuple like lists.

Where to use tuples:
  • Iterating through touple is slightly faster than lists. If you have all constant set of values, use a tuple instead of a list. 
  • Since all data in a tuple are immutable, we can use it as write protected list of variables. 
  • For a dictionary key, we can use integers, Strings, and tuples. A key should be unique and should not be changed. That’s why tuple is used as all elements are immutable. But don’t use tuple of list as key for a dictionary, because list elements can be changed, so it will count as mutable.
Creating a python tuple:
We can create a tuple exactly the same way as list, the only difference is that for lists we use square brackets and for tuples we use parentheses or without parentheses. Each element in a tuple is separated by a comma.

tuple1 = 1, 2, 3, 4, 5 #result : (1, 2, 3, 4, 5)
tuple2 = (1, 2, 3, 4, 5) #result : (1, 2, 3, 4, 5)
tuple3 = (1, "two", 3.0, 4, 5) #result : (1, 'two', 3.0, 4, 5)
 
print tuple1
print tuple2
print tuple3
To create an empty tuple, we can use empty parentheses. To create a tuple with only one element, we should use a comma after that element, otherwise, python will assume it as an integer.
 
Let’s try :

tuple1 = (1,)
print type(tuple1) # output : <type 'tuple'>
 
tuple2 = (1)
print type(tuple2) # output : <type 'int'>
 
tuple3 = ()
print type(tuple3) #output : <type 'tuple'>
Accessing elements:
For accessing an element inside a tuple, we use square brackets [index] like lists. The index starts from ‘0’ for tuples, i.e. the first element has index ‘0’, second element has ‘1’ and so on.  If we have one tuple as an element of a different tuple, we can use two square brackets to access a child tuple’s element.

The following example will clarify your doubts:

tuple1 = (1, 2, 3, 4, 5)
 
print tuple1[0] # result : 1
print tuple1[4] # result : 5
 
tuple2 = (1 , 2, (3, 4, 5))
print tuple2[2][1] # result : 4

Negative indexing and Slicing:

Tuple supports negative indexing like lists. If you use a negative index, the length of the tuple will be added to it,i.e. ‘-1’ index means the last element of the tuple, ‘-2’ means the second last and so on.
 
Using slicing, we can get a list of elements between two index. Column ‘:’ is used for slicing e.g.  tuple_name[start_position : end_position ]

tuple1 = (1, 2, 3, 4, 5)
 
print tuple1[-1] # result : 5
print tuple1[-2] # result : 4
print tuple1[0 : 3] # result : (1, 2, 3)
Updating Python Tuple Elements:
Tuple is immutable, i.e. we cannot modify it. But if one of its element is mutable, like list, we can change its elements.

tuple1 = (1, 2, 3, (4, 5, 6))
print tuple1 # result : (1, 2, 3, (4, 5, 6))
 
tuple1[3][0] = -1
print tuple1 # result : (1, 2, 3, (-1, 5, 6))
We can also perform concatenation on two tuples using plus ( + ) operator. Using * operator, the elements of a tuple can be repeated for ’n’ number of times. Both these operations create a different tuple.

tuple1 = (1, 2, 3, 4, 5)
tuple2 = (6, 7, 8, 9)
 
print tuple1+tuple2 # output : (1, 2, 3, 4, 5, 6, 7, 8, 9)
print tuple1*2 # output : (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Deleting a tuple:
We cannot delete a particular element of a tuple but we can delete the whole tuple.
Using the ‘del’ keyword, tuple can be deleted.

tuple1 = (1, 2, 3, 4, 5)
 
del tuple1
 
print tuple1
The above program will throw a “nameError” as ‘tuple1’ is already deleted and we are trying to print it after that.

Count, Index, Membership and looping:

  • To get the number of items equal to a specific item x, we use count(x) method.
  • To get the index of the first item equal to x in a tuple, use index(x) method.
  • To check if a particular item exist or not in a tuple, use ‘in’ keyword
  • To iterate through a tuple, use ‘for’ loop.

tuple1 = (1, 2, 3, 4, 5, 1, 1, 2, 3)
 
print tuple1.count(1) # output : 3
print tuple1.index(5) # output : 4
 
print 1 in tuple1 # output : True
print 10 in tuple1 # output : False
 
# iterate using for loop
for element in tuple1 :
    print element # This will print all elements of tuple1

Other Built in function of Tuple :
  • cmp(tuple1 , tuple2 ) : Compare elements of both tuples
  • len(tuple) : get the length of ‘tuple’
  • max(tuple) : get max element of ‘tuple’
  • min(tuple) : get min element of ‘tuple’
  • tuple(list) : convert a list into a tuple
tuple1 = (1, 2, 3, 4, 5, 1, 1, 2, 3)
tuple2 = (3, 4, 5, 1, 1, 2, 3)
tuple3 = (1, 2, 3, 4, 5, 1, 1, 2, 3)
mylist = [1,2,3]
 
print cmp(tuple1,tuple2) # output : -1
print cmp(tuple1,tuple3) # output : 0
 
print len(tuple1) # output : 9
 
print max(tuple1) # output : 5
print min(tuple1) # output : 1
 
#converting the list into tuple
mytuple = tuple(mylist)
 
print mytuple # output : (1,2,3)

 

Python Tutorial : Part 6 : Python List module

Python List:

Sequence is the basic data structure used in python. There are 6 sequence types: strings, Unicode Strings, lists, tuples, buffers and xrange objects. The list is a most versatile datatype among these. In this tutorial, we will learn different operations we can perform on a list. 

Create a list in python:
List items are written within a square bracket [ ] , separating each value by a comma. A list can have any number of items and it is not required that each item should be of same data type.

We can even put a list inside a list as an item, known as nested list.

list1 = [1, 2, 3, 4, 5]

list2 = [1, "two", 3.0]


list3 = [1, 2, [3, 4, 5] ]

print list1

print list2

print list3

Every time [ ] expression is executed, python creates a new list. So,

list1 = list2 = [1, 2, 3]

list3 = list1

in this example, list1, list2, and list3 will point to the same list in memory.

 

Accessing elements in a python list:

 

Length of a python list:

 

len(list_name) returns the length of a list.
list1 = [1, 2, 3, 4, 5]
print len(list1)

It will return 5.

 

Item at index i:

 

use list_name[i] to get a specific item at index ‘i’. The first index is ‘0’. 
list1 = [1, 2, 3, 4, 5]
print list1[2]

The output will be 3.

 

Items between ‘i’ and ‘j’:

 

list_name[i : j] returns a new list with items between index ‘i’ and ‘j’
list1 = [1, 2, 3, 4, 5]
print list1[2 : 4]

it will return [3 , 4]

 

Negative indexing:

 

If we use negative indexing, like list_name[ -1 ], the length of the list will be added to that index, i.e. -1 will point to the last element of the list. And -2 will last second element.
list1 = [1, 2, 3, 4, 5]
print list1[-2]

It will print 4.

 

Slice Operation:

Python lists also support slicing. e.g. list_name[ start position : stop position : slicing step ] 

list1 = [1, 2, 3, 4, 5, 6 , 7]
print list1[: : 3]
print list1[1 : 5 : 2]
This program will give the following output:
[1, 4, 7]
[2, 4]

Modify a list in python:
 

Change an element:

we can directly change an element by accessing it through its index as list_name[ i ] or to change a sub-list of elements, use list_name[ start : end ]

 

list1 = [1, 2, 3, 4, 5, 6 , 7]
list1[0] = 0
 
print list1
 
list1[1 : 7] = [1, 2, 3, 4, 5, 6]
 
print list1
Output :
[0, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6]
Add remove element:
For adding one item to a list, use append( ) method. To add several items, use extend( ) method.
list1 = [1, 2, 3, 4, 5, 6 , 7]
list1.append(8)
 
print list1
 
list1.extend([9, 10 , 11])
print list1
output :
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Create a copy:
To create a copy of a list easily, we can use the slicing operation as seen above:
list1 = [1, 2, 3, 4, 5, 6 , 7]
list2 = list1[:]

It will create a copy of list1 and assign it to list2

 

Inserting and deleting value in a list:
  • use list_name.insert( index , item ) to insert a value. 
  • We can also use list_name[first : last ] = [ ] to insert a sequence of items.
  • To delete use del list_name[ i ] or del list_name[ start : end ]
  • We can also use pop() to remove an item. Only pop() will remove the last item. to remove a specific item, use pop (index). 
  • To remove an item with its name, use list_name.remove(item_name)
list1 = [1, 2, 3, 4, 5, 6 , 7]
list1.insert(0 , 0)
 
print list1 #[0, 1, 2, 3, 4, 5, 6, 7]
 
list1[ 8 : 10 ] = [8 , 9]
print  list1 #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
del list1[0]
print list1 #[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
del list1[6 : 9]
print list1 #[1, 2, 3, 4, 5, 6]
 
list1.pop()
list1.pop(0)
print list1 #[2, 3, 4, 5]
 
list1.remove(3)
print list1 #[2, 4, 5]
Other methods in a list :
  • list_name.index(x) : get the index of the first element equal to x
  • list_name.count(x) : get how many times ‘x’ appeared in the list 
  • list_name.sort() : sort items in a list
  • list_name.reverse() : reverse a list
list1 = [1, 2, 3, 4, 5, 6 , 7, 1, 2, 3, 4 , 5, 6, 7]
print list1.index( 4 ) # 3
 
print list1.count( 5 )# 2
 
list1.sort()
print list1 # [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]
 
list1.reverse()
print list1 # [7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1]
Looping through a python list:
Using a for loop, we can iterate through a list
list1 = [ "first", "second", "third" ]
for number in list1:
    print ("Current number "+number)
Output :
Current number first
Current number second
Current number third
Basic operations on python list :
For concatenate two lists, we can use ‘+’ sign and to repeat a list ‘x’ no. of times, we can use list_name * x:
list1 = [1, 2, 3]
list2 = [ 4 ]
 
print list1 + list2 # [1, 2, 3, 4]
 
print list2 * 4 # [4, 4, 4, 4]

Python tutorial : Part 5 : python math module

Python Math module:

Using Math module in python, we can access to different mathematical functions already defined by the C standard . “math” module functions cannot use with complex numbers. For complex numbers, another module known as “cmath” (link) is available.

To use this module , we need to include “import math” for that program. e.g. :

import math
print math.pi

Following are the functions provided by math module :

ceil(x) ,return smallest integer value greater than or equal to x

copysign(x,y) , returns x with the sign of y . e.g. copysign(1.0, -2.0) returns -1.0


fabs(x) : returns absolute value of x


factorial(x) : returns x factorial .If x is not integral or negative, it throws an error.


floor(x) : returns the largest integer value less than or equal to x


fmod(x,y) : returns reminder when x is divided by y


frexp(x) : Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e


fsum(iterable) : Return an accurate floating point sum of values in the iterable.


isinf(x) : Checks if the float x is positive or negative infinity.


isnan(x) : checks if the float x is NaN ( Not a number )


ldexp(x,i) : return x * (2**i). This is essentially the inverse of function frexp().


modf(x) : returns the factional and integer parts of x.


trunc(x) : returns the truncated int value of x

Power and logerithmic functions :

exp(x) : returns e**x


expm1(x) : returns e**x - 1


log(x[, base]) : returns the logarithm of x to the base ( default base is e )


log1p(x) : return the natural logarithm of 1+x (base e).


log10(x) : return the base-10 logarithm of x


pow(x,y) : return x raised to the power y


sqrt(x) : return the square root of x

Trigonometric functions :

acos(x) : return the arc cosine of x in radians

asin(x) : return the arc sine of x in radians

atan(x) : return the arc tangent of x in radians

atan2(y,x) : Returns atan(y / x)

cos(x) : returns the cosine of x

hypot(x, y) : Return the Euclidean norm, sqrt(x*x + y*y).

sin(x) : return the sine of x radians

tan(x) : return the tangent of x radians

Angular Conversion :

degrees(x) : Converts angle x from radians to degrees

radians(x) : Converts angle x from degrees to radians

Hyperbolic functions:

acosh(x) : Returns the inverse hyperbolic cosine of x

asinh(x) : Returns the inverse hyperbolic sine of x

atanh(x) : Returns the inverse hyperbolic tangent of x

cosh(x) : Returns the hyperbolic cosine of x

sinh(x) : Returns the hyperbolic cosine of x

tanh(x) : Returns the hyperbolic tangent of x

Special Functions :

erf(x) : Returns the error function at x

erfc(x) : Returns the complementary error function at x

gamma(x) : Returns the Gamma function at x

lgamma(x) : Returns the natural logarithm of the absolute value of the Gamma function at x

Constants :

pi: Mathematical constant to available precision (3.14159...)

e : mathematical constant e to available precision (2.71828...)

 

 

Python Tutorial : Part 4 : Python Numbers

Python Numbers: 

Numbers are immutable datatype that is used to store numeric values. Python supports four different types of numeric types: integer, long, float and complex numbers. Long is available only in python 2.x, but not in 3.x.

Integer is abbreviated to int. An integer is a whole number. e.g. 2, 3, 0, -7 all are integers. 2 is an integer but 2.0 is not. They are known as float in python. So, integer and floats are separated by the presence or absence of a decimal point.

Long integers are denoted by appending an ‘L’ or ‘l’ after a number. Like 1L or 2L are long integers. It is recommended to use ‘L’ instead of ‘l’ as ‘l’ and ‘1’ can be mismatched. 


We can use isinstance() function to check if a number is of a particular datatype.
print isinstance(0,int)
print isinstance(1,int)
print isinstance(-7,int)
print isinstance(0L,int)
print isinstance(0L,long)

For the above program, the results will be:

 

True
True
True
False
True

Mathematical Operations with Integers :

 

a) Addition ( + ), Subtraction ( – ), Multiplication( * ) and Division ( / ):
Order : Multiplication and Division are done first. Then addition and substraction.
Division: The result will always a float
print (2+2)
print (2*2)
print (2*2-2)
print (2/2-2)
print (4*2/2-2)
print (5*3/5-2+6)
print (5*3/5+2-6)
The answers will be:
4
4
2
-1
2
7
-1
Floor division:
As we have noticed, the division always results a float. Using floor division, we can have an integer. Two forward slashes ( // ) are used for this.
 

Modulo:
Modulo operation is used to get the reminder of a number. Percent sign ( % ) is used for this.

Power:
We can get the power of a number by using two asterisk keys ( ** )
 

print (4 // 2)
print (10 % 3)
print (5 ** 2)
The output will be: 
2
1
25
Binary, Octal, and Hexadecimal: 

In the real word, we normally use decimal or 10 base numbers. But in computer science, mainly Binary, Octal and Hexadecimal numerical system is used. In python, we can represent these numbers by placing a prefix:

 

Binary number ( base 2 ) prefix = ‘0b’ or ‘0B’
Octal number ( base 8 ) prefix = ‘0o’ or ‘0O’
Hexadecimal number ( base 16 ) prefix = ‘0x’ or ‘0X’
print (0B10)
print (0B10 + 0B10)
print (0o12)
print (0o12 + 0o12)
print (0xFE)
print (0xFE + 0xFE)
The output will be:
2
4
10
20
254
508
Python floats:

Integers are only positive numbers, 0 and negative numbers. i.e. they are whole numbers, not real numbers. To represent real numbers like 2.4, 4.0 etc, we use floats in python. 2 is an integer but 2.0 is a float.

The arithmetic operations we have performed for integers are also worked for floats.

print ( 2.3 + 2.4 )
print ( 5.4 - 2.1 )
print ( 4.4 * 1.1 )
print ( 4.4 / 2.2 )
print ( 4.4 // 2.2 )
print ( 4.4 % 2.2 )
print ( 1.1 ** 1.1 )
The output will be:
4.7
3.3
4.84
2.0
2.0
0.0
1.11053424105
Complex Numbers:
Complex numbers are represented as a + bj in python where ‘a’ and ‘ b’ are real number, ‘j’ is an imaginary number. ‘a’ and ‘b’ both treated as floats. We cannot use ‘j’ without ‘b’. To get the real part of an imaginary number, use ‘.real’ and to get the imaginary part, use ‘.imag’.
print ( 1 + 3j )
# print ( 2 + j ) #it will throw an error
print ( (1 + 2j).real )
print ( ( 1 + 2j).imag )
The output will be:
(1+3j)
1.0
2.0

Conversion :

We can convert one number type into another. Built in function int( ) , float( ), complex( ) are used to convert from one type to another.

 

print int(3.4)
print float(4)
print complex(3)
print (1 + 3.0)
Following will be the output:
3
4.0
(3+0j)
4.0

In the fourth case, you can see that if one integer is added with a float, the result will also be a float.

 

Decimal :

Open a terminal, type “python” and hit enter. Now write “0.1 + 0.2” and hit enter. You can see the output is 0.30000000000000004. Shouldn’t it 0.3 only?

 

This is not a bug, it is because floating point numbers are represented as base 2 in computer hardware. Check this link for more information:

 

To overcome this problem, we can use Decimal class of python. Using this class, we can do mathematical operations normally. 
from decimal import Decimal as D
 
a = '0.1'
b = '0.2'
 
print ("adding "+str((D(a)+D(b))))
print ("multiplying "+str((D(a) * D(b))))
Above program will result: 
adding 0.3
multiplying 0.02

Remember that floating point operations are always faster than Decimal operations.

 

Fractions and mathematics:
Fraction:
Fraction has a numerator and denominator.  Python has a fraction module we can use to create fraction from numbers. The following example will explain you how:
 

import fractions
 
for numerator,denominator in [ (2,3),(4,5),(6,7)] :
    f = fractions.Fraction( numerator, denominator )
    print ' %s/%s = %s ' % ( numerator, denominator , f)

The output will be :

 

 2/3 = 2/3
 4/5 = 4/5
 6/7 = 6/7
We can also use fraction for Strings:
import fractions
 
for s in [ '2/3','4/5','6/7'] :
    f = fractions.Fraction( s )
    print ' %s = %s ' % ( s , f)
The result will be same as above. 
Strings can also be used that are in the form <digits>.<digits>.
import fractions
 
for s in [ '2.3','4.5','6.7'] :
    f = fractions.Fraction( s )
    print ' %s = %s ' % ( s , f)
Output : 
 2.3 = 23/10
 4.5 = 9/2
 6.7 = 67/10
For floating point values , it may yield the unexpected result:
import fractions
 
print 'Fraction of 0.1 ',fractions.Fraction(0.1)
output is:
Fraction of 0.1  3602879701896397/36028797018963968

We can use decimal.Decimal('0.1’) to get the correct value.

 

Math and Random:
Python has math module that can be used to perform different mathematical calculations and random module to create a random number.
import math
import random
 
print (math.cos(90))
 
print (math.sin(90))
 
print (math.e)
 
print (math.pow(2,10))
 
print (random.random())
 
print (random.randrange(10,20))
Try to run this program and check the result.  

Python Tutorial : Part 3 : Python Datatype

What is Datatype in Python:

Each variable stored in memory has a datatype. Datatypes are actually classes and if you create any variable of a specific datatype, it is an object. Python’s standard datatypes can be grouped into mainly four different classes:

1. Numeric 
2. Sequences
3. Sets
4. Mapping

1.Numeric :
Numeric type includes:

a)  Integer (int): In python, value of an integer can be of unlimited length ( it only depends on the available memory )
b) Long (long): Long integers of unlimited length. But exists only in python 2.x.
c) Float (float): Floating point numbers. Integers and floating point numbers are separated by a decimal point. The maximum no. of places after the decimal for a float is 15 in python.
d) Complex numbers (complex): Complex numbers are represented as ( x + yj ) where x is the real part and y is the imaginary part.

Integer, long, float and complex all are immutable types.

We can use type() function to check which class a variable belongs to.

count1 = 15
print(“count1 type ", type(count1))

count2 = 15.5
print(“count2 type ", type(count2))

count3 = 15 + 6j
print(“count3 type ", type(count3))
Run the above program and you can find the datatype for each variable.

2. Sequences : 

Sequences type includes:

a) Python String (str): String is actually a sequence of 8-bit characters ( in python 2.x ) or a sequence of Unicode characters ( in Python 3.x ). Strings are immutable i.e. we cannot change any character of a String. To represent a String in python, single quote or double quote is used. For multiline strings, a triple quote is used. To print a particular character inside a String, use stringName[position]. Similarly, to print characters in a range, use stringName[firstPosition,lastPosition + 1]

Try to run the following program and check the results:

str1 = 'This is a String'
print str1

str2 = "This is also a String"
print str2

str3 = ''' This is a multiline
String '''
print str3

str4 = """ This is also a multiline
String """
print str4

print("Printing the first character of str1 "+str1[0])
print("Printing the first word of str1 "+str1[0:4])

b) Python list:  
Lists are ordered sequence of variables. A list is mutable, i.e. you can alter any item of a list. Also, list can contain items of different types. To declare a list bracket [] is used. If you want to print or alter a variable inside a list, you can use listname[variablePosition].
Check the following example:

myList = [1,"one",1.0]
print myList

print ("first element of the list is "+str(myList[0]))

myList[0] = "2"

print ("first element is changed")

print ("now , first element is "+myList[0])
At first element was 1. We have changed it to “2”.

c) Python Tuple: 
Python tuple is same as list, the only difference is that it is immutable. To represent tuple in python, we use parentheses ( ). Let’s try with the above example for tuple:

myList = (1,"one",1.0)
print myList

print ("first element of the list is "+str(myList[0]))

myList[0] = "2"

print ("first element is changed")

print ("now , first element is "+myList[0])
It will throw an error on myList[0] = “2” line as we cannot change any values in tuple.

3) Python Sets:

Sets type includes:
a) Set: Set is an unordered collection of unique objects. Each item is separated by a comma inside braces {}.
We can also pass a list to the set function to create a new set.
Check the below example:

mySet1 = set("python")
print mySet1

myList = (1,"one","two")
mySet2 = set(myList)
print mySet2

mySet3 = set([1,1,1,1,1,1])
print mySet3

Output will be like below : 

set(['h', 'o', 'n', 'p', 't', 'y'])
set([1, 'two', 'one'])
set([1])
You can see that mySet3 contains only one “1” as all values of a set should be unique.
We can perform set operations like add, remove, intersection, union etc on sets.

b) Frozen Sets:
Frozen set is similar as set but they are immutable.  You cannot add any new data to frozen set.

myList = [1,2,3,4]

myFrozenSet = frozenset(myList)
print ("Frozen set "+str(myFrozenSet))

4. Python Mapping:

Mapping type includes:

Python Dictionary:
Python Dictionary is a collection of key-value pairs. Dictionary is an unordered collection. To get any value from dictionary, we must know the key. Dictionaries are defined within braces {}. Each element or key-value pairs can be of any type.

Check the example below :
myDictionary = {"key1":'value1',"key2":2}

print ("Element for key key2 "+str(myDictionary["key2"]))
It will print 2 as value for key “key2” is 2. 

 

Python Tutorial : Part 2 : Variables

Python Variable :
Variable is a reserved memory location to store values. You can assume it as a bucket that contains a value. Names of a different variable should be different and unique. The rules for writing variable name is same as we have seen for identifiers. In this python tutorial, we will learn how to assign values to a variable , deleting a variable and concatenation. 

Assigning a value:
In python, equal ( = ) sign is used to assign values to a variable. You don’t need to specify what type of variable this is ( e.g integer, float etc. ), it will happen automatically. Also no need to declare explicitly to reserve a memory location for a variable, you can directly assign a value.

E.g :

count = 10
print count

It will print 10

Reassigning a variable:
Can you reassign a variable? i.e. currently count is an integer and it has a value 10. Can we convert count to a String variable? Yes, we can. This is the beauty of python:

count = 10

count = "This is a String"
print count

The result will be “This is a String”

Multiple Assignment:
Multiple Assignment means assigning different values to different variables in a single line. In python, we can achieve this like below:

a, b, c = 5, 2, 1
a, b, c = 5, 2.0, ”different values"
a, b, c = “same value"

So, you can assign different values or same value to several variables simultaneously.

Delete a variable:
You can also delete a variable using “del” command.

Let’s take a look at the following example:

count = 100
del count

print count

If you will try to run the above script, following error msg will be shown:
NameError: name ‘count’ is not defined

Local and Global Variables:
Global variables are accessible from anywhere in your program. But a Local variable can be accessed only inside a function or method where it is declared.
Let’s take a look into the following program:

myString = "Global String"

def innerFunction():
myString = "Local String"
print myString

innerFunction()
print myString

It will first print “Local String”. myString defined inside innerFunction() is a local variable. So, on calling innerFunction(), it will take the value from the local variable.

myString = "Global String"

def innerFunction():
#myString = "Local String"
print myString

innerFunction()
print myString

What about now? It will print “Global String” twice. As we have commented out the local variable declaration part, it will take the value from the global String.

myString = "Global String"

def innerFunction():
global myString
myString = "Local String"
print myString

innerFunction()
print myString

This time? It will print “Local String” two times. That means we can access Global variables using global keyword and change it inside a function.

myString = "Global String"

def innerFunction():
print myString
myString = "Local String"
print myString

innerFunction()
print myString

Output will be :
UnboundLocalError: local variable ‘myString’ referenced before assignment

Why ? Because we have created one variable myString inside innerFunction. So, python will assume that the first print statement is trying to print the local variable, which is not defined yet and it will throw the above error message.

Concatenation :

count = 100
statement = "Print a number"

print statement,count
print statement+count

Result: The second print statement will throw an error: TypeError: cannot concatenate ‘str’ and ‘int’ objects
So, first, we need to change count to a String variable before concatenating it with another String variable. Let’s check:

count = 100
statement = "Print a number"

print statement,count
print statement+str(count)

Output :

Print a number 100
Print a number100

The only difference is that the first statement has a space between “number” and “100”. The first print statement is actually not a concatenation. We are just passing different arguments to the print function and print joins them with a separator keyword. ( Default is space ).