Saturday, 6 August 2016

4.DATA TYPES IN PYTHON


Data types

Data types are nothing but some of the key words of programming languages, which are used to specify what type of data has to store into the variables.
Python supports dynamic data types. That is the data type of the variable will be decided at runtime based on the data which is assigned to that variable.
Python supports following types of data types internally

     1.numeric types
     2.boolean
     3.string
     4.list
     5.tuple
     6.dictionary
     7.set

1. numeric types:


     Numeric data types store numeric values. Numeric objects are created when you assign a value to them.
Python supports following numeric types
a )      Int
b )      Long
c )      float
d )     complex
eg1:
i=123
print  i #123
print type(i) #int
print id(i) #123459(address)
eg2:
j=123L
print  j #123
print type(j) #long
print id(j) #123499(address)
eg3:
k=123.123
print k #123.123
print type(k) #float
print id(k) #122499(address)
eg4:
x=2.3j
print  x#2.3j
print type(x) #complex
print id(x) #123479(address)

2. Boolean :


Boolean data type is used to represent true/false values
P=True
Print p # True
Print type(p) # bool
Print id(p) # 45678


3. string:


String data type is used to represent group of characters or alphanumeric characters.
Strings we can represent into two ways
1.single quotes
2.triple quotes

1. single quoted string:

Single quoted string is used to represent single line string.
Eg1:
X=’python’
print x # python
print type(x) # str
print id(x) # 1256789
       (or)
Y=”python”
Print y; # python
print type(y) # str
print id(y) # 1296789

eg2:
z=”welcome
error
z=”welcome to \
    python\
   world \
   “
Print z # welcome to python world
              (or)
z=”welcome to \n \
    python \n \
   world \n \
   “
Print z # welcome to
             python
             world

2. triplel quoted string:

Triple quoted string is used to represent multile line string.
Eg1:
X=’’’python’’’
print x # python
print type(x) # str
print id(x) # 13456789
       (or)
Y=”””python”””
Print y; # python
print type(y) # str
print id(y) # 1296789
eg2:
z=”””welcome to
    python
   world
  “””
Print z # welcome to
             python
             world

4.List

The list is a most versatile data type available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.
colors = ['red', 'blue', 'green']
print (colors[0])   ## red
print (colors[2])    ## green
print (len(colors))  ## 3
print ("Creating List:")
colors = ['red', 'blue', 'green']
print (colors[0])   ## red
print (colors[1])   ## blue
print (colors[2])    ## green
print (len(colors))  ## 3

print ("Append to the List")
colors.append("orange")
print (colors[3]) ##orange

print ("Insert to the List")
colors.insert(3, "yellow")
print (colors[3]) ##yellow
print (colors[4]) ##orange

print ("Remove from the List")
print (colors[1])   ## blue
colors.remove("blue") ## deletes blue and shifts elements to the left
print (colors[1])   ## green 

print ("Sorting Ascending order using sorted")
nums = [98,22,45,30]
numsAsc = sorted(nums)
print (numsAsc[0])   ## 22
print (numsAsc[1])   ## 30
print (numsAsc[2])    ## 45

print ("Sorting Descending order using sorted")
numsDesc = sorted(nums,reverse=True)
print (numsDesc[0])   ## 98
print (numsDesc[1])   ## 45
print (numsDesc[2])    ## 30
Using for loops with lists
nos = [1, 4, 9, 16, 25]
sum = 0
for num in nos:
    sum += num
print (sum)  ## 55

Using if loop with lists

colors = ['red', 'blue', 'green']
if 'blue' in colors:
    print ('cool')  # blue found in the list

Using while loops with lists

i = 0
a = [1,2,3,4,5,6,7,8,9]
while i < len(a):
    print (a[i])  #prints 1 4 7
    i = i + 3


List Slices

list = ['a', 'b', 'c', 'd']

  print list[1:-1]   ## ['b', 'c']

  list[0:2] = 'z'    ## replace ['a', 'b'] with ['z']

  print list         ## ['z', 'c', 'd']

 

List Methods


·         list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
·         list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
·         list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
·         list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
·         list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)
·         list.sort() -- sorts the list in place (does not return it). (The sorted() function shown below is preferred.)
·         list.reverse() -- reverses the list in place (does not return it)
·         list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

List Comprehensions

 S = [x**2 for x in range(10)]
Print s
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

V = [2**i for i in range(13)]
Print v
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]

M = [x for x in S if x % 2 == 0]
print M
 [0, 4, 16, 36, 64]


noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in noprimes]
print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
                     

words = 'The quick brown fox jumps over the lazy dog'.split()
print words
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
stuff = [[w.upper(), w.lower(), len(w)] for w in words]
for i in stuff:
     print i

output

['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]
 
5.Python Tuple
In Python programming, tuple is similar to a list.
The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it.
 A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).
my_tuple = ()
my_tuple = (1, 2, 3)
my_tuple = (1, "Hello", 3.4)
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = 3, 4.6, "dog"
a, b, c = my_tuple
Creating a tuple with one element is a bit tricky. Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is in fact a tuple.
>>> my_tuple = ("hello")   # only parentheses is not enough
>>> type(my_tuple)
<class 'str'>
>>> my_tuple = ("hello",)  # need a comma at the end
>>> type(my_tuple)
<class 'tuple'>
>>> my_tuple = "hello",    # parentheses is optional
>>> type(my_tuple)
<class 'tuple'>

 

 

Accessing Elements in a Tuple

There are various ways in which we can access the elements of a tuple.

Indexing

We can use the index operator [] to access an item in a tuple. Index starts from 0. So, a tuple having 6 elements will have index from 0 to 5.
Trying to access an element other that this will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.
 Nested tuple are accessed using nested indexing.
>>> my_tuple = ['p','e','r','m','i','t']
>>> my_tuple[0]
'p'
>>> my_tuple[5]
't'
>>> my_tuple[6]   # index must be in range
...
IndexError: list index out of range
>>> my_tuple[2.0] # index must be an integer
...
TypeError: list indices must be integers, not float
>>> n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
>>> n_tuple[0][3]  # nested index
's'
>>> n_tuple[1][1]  # nested index
4
>>> n_tuple[2][0]  # nested index
1

Negative Indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
>>> my_tuple = ['p','e','r','m','i','t']
>>> my_tuple[-1]
't'
>>> my_tuple[-6]
'p'

Slicing

We can access a range of items in a tuple by using the slicing operator (colon).
>>> my_tuple = ('a','b','c','d','e','f','g','h','i',’j’)
>>> my_tuple[1:4]  # elements 2nd to 4th
('b', 'c', 'd')
>>> my_tuple[:-7]  # elements beginning to 2nd
('a', 'b',’c’)
>>> my_tuple[7:]   # elements 8th to end
('h', 'i',’j’)
>>> my_tuple[:]    # elements beginning to end
('a','b','c','d','e','f','g','h','i',’j’)

Changing or Deleting a Tuple

Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once it has been assigned. But if the element is itself a mutable datatype like list, its nested items can be changed. We can also assign a tuple to different values (reassignment).
>>> my_tuple = (4, 2, 3, [6, 5])
>>> my_tuple[1] = 9  # we cannot change an element
...
TypeError: 'tuple' object does not support item assignment
>>> my_tuple[3] = 9  # we cannot change an element
...
TypeError: 'tuple' object does not support item assignment
>>> my_tuple[3][0] = 9   # but item of mutable element can be changed
>>> my_tuple
(4, 2, 3, [9, 5])
>>> my_tuple = ('a','b','c','d','e','f','g','h','i',’j’)
# tuples can be reassigned
>>> my_tuple
('a','b','c','d','e','f','g','h','i',’j’)
We can use + operator to combine two tuples. This is also called concatenation. The * operator repeats a tuple for the given number of times. These operations result into a new tuple.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> ("Repeat",) * 3
('Repeat', 'Repeat', 'Repeat')
We cannot delete or remove items from a tuple. But deleting the tuple entirely is possible using the keyword del.
>>> my_tuple = ('a','b','c','d','e','f','g','h','i',’j’)
>>> del my_tuple[3] # can't delete items
...
TypeError: 'tuple' object doesn't support item deletion
>>> del my_tuple    # can delete entire tuple
>>> my_tuple
...
NameError: name 'my_tuple' is not defined

Python Tuple Methods:

Methods that add items or remove items are not available with tuple. Only the following two methods are available.
Python Tuple Method
Method
Description
count(x)
Return the number of items that is equal tox
index(x)
Return index of first item that is equal to x
>>> my_tuple = ('a','p','p','l','e',)
>>> my_tuple.count('p')
2
>>> my_tuple.index('l')
3

Tuple Membership Test

We can test if an item exists in a tuple or not, using the keyword in.
>>> my_tuple = ('a','p','p','l','e',)
>>> 'a' in my_tuple
True
>>> 'b' in my_tuple
False
>>> 'g' not in my_tuple
True

Iterating Through a Tuple

Using a for loop we can iterate though each item in a tuple.
>>> for name in ('John','Kate'):
...     print("Hello",name)
...    
Hello John
Hello Kate

Advantage of Tuple over List:

Tuples and list look quite similar except the fact that one is immutable and the other is mutable. We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes. There are some advantages of implementing a tuple than a list. Here are a few of them.
  • Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
  • Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
  • If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.

6.Dictionary:

Python dictionary is an unordered collection of items. While other compound datatypes have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when the key is known.
Ceating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value. While values can be of any datatype and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. We can also create a dictionary using the built-in function dict().

# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
Accessing Elements in a Dictionary
While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. The difference while using get() is that it returns None instead of KeyError, if the key is not found.

>>> my_dict = {'name':'Ranjit', 'age': 26}
>>> my_dict['name']
'Ranjit'

>>> my_dict.get('age')
26

>>> my_dict.get('address')

>>> my_dict['address']
...
KeyError: 'address'
Changing or Adding Elements in a Dictionary
Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

>>> my_dict
{'age': 26, 'name': 'Ranjit'}

>>> my_dict['age'] = 27  # update value
>>> my_dict
{'age': 27, 'name': 'Ranjit'}

>>> my_dict['address'] = 'Downtown'  # add item
>>> my_dict
{'address': 'Downtown', 'age': 27, 'name': 'Ranjit'}
Deleting or Removing Elements from a Dictionary
We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value. The method,popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself.

>>> squares = {1:1, 2:4, 3:9, 4:16, 5:25# create a dictionary

>>> squares.pop(4# remove a particular item
16
>>> squares
{1: 1, 2: 4, 3: 9, 5: 25}

>>> squares.popitem()  # remove an arbitrary item
(1, 1)
>>> squares
{2: 4, 3: 9, 5: 25}

>>> del squares[5# delete a particular item
>>> squares
{2: 4, 3: 9}

>>> squares.clear()  # remove all items
>>> squares
{}

>>> del squares  # delete the dictionary itself
>>> squares
...
NameError: name 'squares' is not defined
Python Dictionary Methods:
Methods that are available with dictionary are tabulated below. Some of them have already been used in the above examples.
Python Dictionary Methods
Method
Description
clear()
Remove all items form the dictionary.
copy()
Return a shallow copy of the dictionary.
fromkeys(seq[, v])
Return a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d])
Return the value of key. If keydoesnot exit, return d (defaults toNone).
items()
Return a new view of the dictionary's items (key, value).
keys()
Return a new view of the dictionary's keys.
pop(key[,d])
Remove the item with key and return its value or d if key is not found. If d is not provided andkey is not found, raisesKeyError.
popitem()
Remove and return an arbitary item (key, value). Raises KeyErrorif the dictionary is empty.
setdefault(key[,d])
If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys.
values()
Return a new view of the dictionary's values
Here are a few example use of these methods.

>>> marks = {}.fromkeys(['Math','English','Science'], 0)
>>> marks
{'English': 0, 'Math': 0, 'Science': 0}

>>> for item in marks.items():
...     print(item)
...   
('English', 0)
('Math', 0)
('Science', 0)

>>> list(sorted(marks.keys()))
['English', 'Math', 'Science']
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create new dictionary from an iterable in Python. Dictionary comprehension consists of an expression pair (key: value) followed by for statement inside curly braces {}. Here is an example to make a dictionary with each item being a pair of a number and its square.

>>> squares = {x: x*x for x in range(6)}
>>> squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to

squares = {}
for x in range(6):
   squares[x] = x*x
A dictionary comprehension can optionally contain more for or if statements. An optional if statement can filter out items to form the new dictionary. Here are some examples to make dictionary with only odd items.

>>> odd_squares = {x: x*x for x in range(11) if x%2 == 1}
>>> odd_squares
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Other Dictionary Operations
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is for keys only, not for values.

>>> squares
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
>>> 1 in squares
True

>>> 2 not in squares
True

>>> # membership tests for key only not value
>>> 49 in squares
False
Iterating Through a Dictionary
Using a for loop we can iterate though each key in a dictionary.

>>> squares
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
>>> for i in squares:
...     print(squares[i])
...   
1
9
81
25
49

Dictionary comprehension
>>> D = {x: x**2 for x in [1,2,3,4,5]}
>>> D
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

>>> D = {x.upper(): x*3 for x in 'abcd'}
>>> D
{'A': 'aaa', 'C': 'ccc', 'B': 'bbb', 'D': 'ddd'}
When we want initialize a dict from keys, we do this:
>>> D = dict.fromkeys(['a','b','c'], 0)
>>> D
{'a': 0, 'c': 0, 'b': 0}

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

7.Set
Set is an unordered collection of items. Every element is unique (no duplicates). However, the set itself is mutable (we can add or remove items). Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.

>>> # set of integers
>>> my_set = {1, 2, 3}

>>> # set of mixed datatypes
>>> my_set = {1.0, "Hello", (1, 2, 3)}

>>> # set donot have duplicates
>>> {1,2,3,4,3,2}
{1, 2, 3, 4}

>>> # set cannot have mutable items
>>> my_set = {1, 2, [3, 4]}
...
TypeError: unhashable type: 'list'

>>> # but we can make set from a list
>>> set([1,2,3,2])
{1, 2, 3}
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument.

>>> a = {}
>>> type(a)
<class 'dict'>
>>> a = set()
>>> type(a)
<class 'set'>
Changing a Set in Python
Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set using indexing or slicing. Set does not support it. We can add single elements using the method add(). Multiple elements can be added using update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.

>>> my_set = {1,3}
>>> my_set[0]
...
TypeError: 'set' object does not support indexing
>>> my_set.add(2)
>>> my_set
{1, 2, 3}
>>> my_set.update([2,3,4])
>>> my_set
{1, 2, 3, 4}
>>> my_set.update([4,5], {1,6,8})
>>> my_set
{1, 2, 3, 4, 5, 6, 8}
Removing Elements from a Set
A particular item can be removed from set using methods like discard() and remove(). The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition. The following example will illustrate this.

>>> my_set = {1, 3, 4, 5, 6}
>>> my_set.discard(4)
>>> my_set
{1, 3, 5, 6}
>>> my_set.remove(6)
>>> my_set
{1, 3, 5}
>>> my_set.discard(2)
>>> my_set
{1, 3, 5}
>>> my_set.remove(2)
...
KeyError: 2
Similarly, we can remove and return an item using the pop() method. Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary. We can also remove all items from a set using clear().

>>> my_set = set("HelloWorld")
>>> my_set.pop()
'r'
>>> my_set.pop()
'W'
>>> my_set
{'d', 'e', 'H', 'o', 'l'}
>>> my_set.clear()
>>> my_set
set()
Python Set Operation
Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods. Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union

 

Union of A and B is a set of all elements from both sets. Union is performed using |operator. Same can be accomplished using the method union().

>>> A | B
{1, 2, 3, 4, 5, 6, 7, 8}
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> B.union(A)         
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection


Intersection of A and B is a set of elements that are common in both sets. Intersection is performed using & operator. Same can be accomplished using the method intersection().

>>> A & B
{4, 5}
>>> A.intersection(B)
{4, 5}
>>> B.intersection(A)
{4, 5}
Set Difference

 

Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of element in B but not in A. Difference is performed using -operator. Same can be accomplished using the method difference().

>>> A - B
{1, 2, 3}
>>> A.difference(B)
{1, 2, 3}
>>> B - A
{8, 6, 7}
>>> B.difference(A)
{8, 6, 7}
Set Symmetric Difference


Symmetric Difference of A and B is a set of element in both A and B except those common in both. Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference().
        
>>> A ^ B
{1, 2, 3, 6, 7, 8}
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with set objects.
Python Set Methods
Method
Description
add()
Add an element to a set
clear()
Remove all elemets form a set
copy()
Return a shallow copy of a set
difference()
Return the difference of two or more sets as a new set
difference_update()
Remove all elements of another set from this set
discard()
Remove an element from set if it is a member. (Do nothing if the element is not in set)
intersection()
Return the intersection of two sets as a new set
intersection_update()
Update the set with the intersection of itself and another
isdisjoint()
Return True if two sets have a null intersection
issubset()
Return True if another set contains this set
issuperset()
Return True if this set contains another set
pop()
Remove and return an arbitary set element. Raise KeyError if the set is empty
remove()
Remove an element from a set. It the element is not a member, raise a KeyError
symmetric_difference()
Return the symmetric difference of two sets as a new set
symmetric_difference_update()
Update a set with the symmetric difference of itself and another
union()
Return the union of sets in a new set
update()
Update a set with the union of itself and others
Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the keyword in.

>>> my_set = set("apple")
>>> 'a' in my_set
True
>>> 'p' not in my_set
False
Iterating Through a Set
Using a for loop we can iterate though each item in a set.

>>> for letter in set("apple"):
...     print(letter)
...   
a
p
e
l

set comprehension
>>> s = { x for x in range(10) }
>>> s 
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


No comments:

Post a Comment