In [48]:
Agenda = '''
Dictionary
Dictionary Case Study
iterator, generator
Built in Functions
lambda, 
filter, 
map,
set,
enumerate,
sorted, 
reversed, 
range
zip,
sum,
max,
min 
List Comprehension 
Dictionary Comprehension
'''

Dictionary

Dictionary is an unorder collection of unique, immutable

key and mutable or immutable value pairs.

In [2]:
Dict1 = {}

Dict1['name'] = 'Surendra'
Dict1
Out[2]:
{'name': 'Surendra'}
In [3]:
Dict1[['city','state']] = ['Pune','Maharashtra']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-8c3138923cfa> in <module>
----> 1 Dict1[['city','state']] = ['Pune','Maharashtra']

TypeError: unhashable type: 'list'
In [4]:
Dict1[('city','state')] = ['Pune','Maharashtra']
In [5]:
Dict1
Out[5]:
{'name': 'Surendra', ('city', 'state'): ['Pune', 'Maharashtra']}
In [6]:
Dict1.keys()
Out[6]:
dict_keys(['name', ('city', 'state')])
In [7]:
Dict1.values()
Out[7]:
dict_values(['Surendra', ['Pune', 'Maharashtra']])
In [8]:
Dict1[41]  = {'a' : 'apple','b' : 'banana'}
In [9]:
Dict1
Out[9]:
{'name': 'Surendra',
 ('city', 'state'): ['Pune', 'Maharashtra'],
 41: {'a': 'apple', 'b': 'banana'}}
In [10]:
Fruits = { 'o' : 'orange', 'g' : 'grape' }
In [11]:
Fruits.update(Dict1)
Fruits
Out[11]:
{'o': 'orange',
 'g': 'grape',
 'name': 'Surendra',
 ('city', 'state'): ['Pune', 'Maharashtra'],
 41: {'a': 'apple', 'b': 'banana'}}
In [12]:
Fruits.keys()
Out[12]:
dict_keys(['o', 'g', 'name', ('city', 'state'), 41])
In [13]:
Fruits.get('o')
Out[13]:
'orange'
In [14]:
dir(Fruits)
Out[14]:
['__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']
In [15]:
Fruits.pop(('city', 'state'))
Out[15]:
['Pune', 'Maharashtra']
In [16]:
Fruits
Out[16]:
{'o': 'orange',
 'g': 'grape',
 'name': 'Surendra',
 41: {'a': 'apple', 'b': 'banana'}}
In [17]:
Fruits.popitem()
Out[17]:
(41, {'a': 'apple', 'b': 'banana'})
In [18]:
Fruits
Out[18]:
{'o': 'orange', 'g': 'grape', 'name': 'Surendra'}
In [19]:
Fruits['name'] = 'Fruits_name'
In [20]:
Fruits
Out[20]:
{'o': 'orange', 'g': 'grape', 'name': 'Fruits_name'}

Dictionary Case Study

Objectives

   1. Create Library Application using Dictionary
   2. Create Menu for Books, Publishers and Authors
   3. Display Many to Many Relationship between Book and Authors.
   4. Display One-to-One Relationship between Book and publisher. 
   5. Create Library Dictionary using Books Dictionary
   6. Update Library Dictionary by updating Books keys and values. 
   7. Access Second Author First Name and Update with new name. 
   8. Display list of Authors, Publishers, Titles from 
   Library Dictionary
   9. Take Input Data from User using Menu and Input statement and Update Library Dictionary. 
In [21]:
Menu = '''
1. Create Library Application using Dictionary
   2. Create Menu for Books, Publishers and Authors
   3. Display Many to Many Relationship between Book and Authors.
   4. Display One-to-One Relationship between Book and publisher. 
   5. Create Library Dictionary using Books Dictionary
   6. Update Library Dictionary by updating Books keys and values. 
   7. Access Second Author First Name and Update with new name. 
   8. Display list of Authors, Publishers, Titles from 
   Library Dictionary
   9. Take Input Data from User using Menu and Input statement and Update Library Dictionary. 
'''
In [22]:
print(Menu)
1. Create Library Application using Dictionary
   2. Create Menu for Books, Publishers and Authors
   3. Display Many to Many Relationship between Book and Authors.
   4. Display One-to-One Relationship between Book and publisher. 
   5. Create Library Dictionary using Books Dictionary
   6. Update Library Dictionary by updating Books keys and values. 
   7. Access Second Author First Name and Update with new name. 
   8. Display list of Authors, Publishers, Titles from 
   Library Dictionary
   9. Take Input Data from User using Menu and Input statement and Update Library Dictionary. 

In [23]:
while True:
    op = int(input("Enter your choice:"))
    if op == 1:
        print("Create Library Application using Dictionary")
    elif op == 2:
        print("Create Menu for Books, Publishers and Authors")
    elif op == 3:
        print("Display Many to Many Relationship between Book and \
              Authors.")
    elif op == 4:
        print("Exit")
        break
    else:
        print("Select 1 - 9 option only")
Enter your choice:1
Create Library Application using Dictionary
Enter your choice:4
Exit
In [24]:
run BooksApp.py
*** Publishers Dictionary ****

{'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}
{'pid': 2, 'pname': 'BPB Pub', 'pcity': 'Delhi', 'pweb': 'https://www.bpb.org'}
{'pid': 3, 'pname': 'TataMcgraw Pub', 'pcity': 'Mumbai', 'pweb': 'https://www.tatamcgraw.org'}


*** Publishers Dictionary ****

{'P1': {'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}, 'P2': {'pid': 2, 'pname': 'BPB Pub', 'pcity': 'Delhi', 'pweb': 'https://www.bpb.org'}, 'P3': {'pid': 3, 'pname': 'TataMcgraw Pub', 'pcity': 'Mumbai', 'pweb': 'https://www.tatamcgraw.org'}}


*** Authors Dictionary ****

{'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}
{'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}
{'first_name': 'Satish', 'last_name': 'Panpaliya', 'city': 'Chicago', 'email': 'satish@gktcs.com'}


*** Authors Dictionary ****

{'A1': {'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}, 'A2': {'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}, 'A3': {'first_name': 'Satish', 'last_name': 'Panpaliya', 'city': 'Chicago', 'email': 'satish@gktcs.com'}}
*** Books Dictionary ****



{'title': 'Bytes of Python', 'publisher': {'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}, 'authors': [{'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}, {'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}], 'pub_date': '21-09-2019'}
**** Books Library***
In [25]:
run Bookdict.py
{'P1': {'pid': 1, 'pname': 'Orielly', 'pcity': 'Bangalore', 'pweb': 'www.orielly.org'}, 'P2': {'pid': 2, 'pname': 'Tata', 'pcity': 'Chennai', 'pweb': 'www.tata.org'}, 'P3': {'pid': 3, 'pname': 'willey', 'pcity': 'Delhi', 'pweb': 'www.willey.org'}, 'P4': {'pid': 4, 'pname': 'bpb', 'pcity': 'Pune', 'pweb': 'www.bpb.org'}}
{'A1': {'id': 1, 'fname': 'Surendra', 'lname': 'Panpaliya', 'city': 'Pune'}, 'A2': {'id': 2, 'fname': 'Satish', 'lname': 'Panpaliya', 'city': 'Bangalore'}, 'A3': {'id': 3, 'fname': 'Suresh', 'lname': 'Patil', 'city': 'Bangalore'}}
In [28]:
# %load BooksApp.py
'''
Dictionary Application will consist of 
Books Dictionay, 
Authors Dictionary and 
Publishers Dictionary. This will include relation of 
Authors with Book ( Many to Many )
Relation of Publisher with Book ( One to One )
'''

# Step 1. Create Publisher Dictionary 

print("*** Publishers Dictionary ****\n")

Publisher1 = { 'pid' : 1, 'pname' : 'Orielly Pub',
              'pcity' : 'Chennai', 
              'pweb' : 'https://www.orielly.org' }

print(Publisher1)

Publisher2 = { 'pid' : 2, 'pname' : 'BPB Pub',
              'pcity' : 'Delhi', 
              'pweb' : 'https://www.bpb.org' }

print(Publisher2)

Publisher3 = { 'pid' : 3, 'pname' : 'TataMcgraw Pub',
              'pcity' : 'Mumbai', 
              'pweb' : 'https://www.tatamcgraw.org' }

print(Publisher3)

Publishers = {}
Publishers['P1'] = Publisher1
Publishers['P2'] = Publisher2
Publishers['P3'] = Publisher3

print("\n")
print("*** Publishers Dictionary ****\n")
print(Publishers)

# Step2 Create Authors Dictionary


print("\n")
print("*** Authors Dictionary ****\n")

Author1 = {'first_name' : 'Surendra', 
           'last_name' : 'Panpaliya',
          'city' : 'Pune',
          'email' : 'surendra@gktcs.com' }

print(Author1)

Author2 = {'first_name' : 'Narendra', 
           'last_name' : 'Panpaliya',
          'city' : 'Pune',
          'email' : 'narendra@gktcs.com' }

print(Author2)

Author3 = {'first_name' : 'Satish', 
           'last_name' : 'Panpaliya',
          'city' : 'Chicago',
          'email' : 'satish@gktcs.com' }

print(Author3)

Authors = { }

Authors['A1'] = Author1

Authors['A2'] = Author2

Authors['A3'] = Author3

print("\n")

print("*** Authors Dictionary ****\n")

print(Authors)

print("*** Books Dictionary ****\n")

print("\n")

Book1 = { 'title' : 'Bytes of Python',
        'publisher' : Publishers['P1'], 
        'authors' : [ Authors['A1'], Authors['A2'] ],
        'pub_date' : '21-09-2019' }


Book2 = { 'title' : 'Django',
        'publisher' : Publishers['P2'], 
        'authors' : [ Authors['A2'], Authors['A3'] ],
        'pub_date' : '20-09-2019' }


Book3 = { 'title' : 'Data Science',
        'publisher' : Publishers['P3'], 
        'authors' : [ Authors['A1'], Authors['A3'] ],
        'pub_date' : '23-09-2019' }


Books = { }

Books['B1'] = Book1

print(Books['B1'])

Books['B2'] = Book2

Books['B3'] = Book3


print("**** Books Library***")

Books
*** Publishers Dictionary ****

{'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}
{'pid': 2, 'pname': 'BPB Pub', 'pcity': 'Delhi', 'pweb': 'https://www.bpb.org'}
{'pid': 3, 'pname': 'TataMcgraw Pub', 'pcity': 'Mumbai', 'pweb': 'https://www.tatamcgraw.org'}


*** Publishers Dictionary ****

{'P1': {'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}, 'P2': {'pid': 2, 'pname': 'BPB Pub', 'pcity': 'Delhi', 'pweb': 'https://www.bpb.org'}, 'P3': {'pid': 3, 'pname': 'TataMcgraw Pub', 'pcity': 'Mumbai', 'pweb': 'https://www.tatamcgraw.org'}}


*** Authors Dictionary ****

{'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}
{'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}
{'first_name': 'Satish', 'last_name': 'Panpaliya', 'city': 'Chicago', 'email': 'satish@gktcs.com'}


*** Authors Dictionary ****

{'A1': {'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}, 'A2': {'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}, 'A3': {'first_name': 'Satish', 'last_name': 'Panpaliya', 'city': 'Chicago', 'email': 'satish@gktcs.com'}}
*** Books Dictionary ****



{'title': 'Bytes of Python', 'publisher': {'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}, 'authors': [{'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}, {'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}], 'pub_date': '21-09-2019'}
**** Books Library***
Out[28]:
{'B1': {'title': 'Bytes of Python',
  'publisher': {'pid': 1,
   'pname': 'Orielly Pub',
   'pcity': 'Chennai',
   'pweb': 'https://www.orielly.org'},
  'authors': [{'first_name': 'Surendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'surendra@gktcs.com'},
   {'first_name': 'Narendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'narendra@gktcs.com'}],
  'pub_date': '21-09-2019'},
 'B2': {'title': 'Django',
  'publisher': {'pid': 2,
   'pname': 'BPB Pub',
   'pcity': 'Delhi',
   'pweb': 'https://www.bpb.org'},
  'authors': [{'first_name': 'Narendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'narendra@gktcs.com'},
   {'first_name': 'Satish',
    'last_name': 'Panpaliya',
    'city': 'Chicago',
    'email': 'satish@gktcs.com'}],
  'pub_date': '20-09-2019'},
 'B3': {'title': 'Data Science',
  'publisher': {'pid': 3,
   'pname': 'TataMcgraw Pub',
   'pcity': 'Mumbai',
   'pweb': 'https://www.tatamcgraw.org'},
  'authors': [{'first_name': 'Surendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'surendra@gktcs.com'},
   {'first_name': 'Satish',
    'last_name': 'Panpaliya',
    'city': 'Chicago',
    'email': 'satish@gktcs.com'}],
  'pub_date': '23-09-2019'}}
In [29]:
Books.keys()
Out[29]:
dict_keys(['B1', 'B2', 'B3'])
In [31]:
Books['B2'].keys()
Out[31]:
dict_keys(['title', 'publisher', 'authors', 'pub_date'])
In [34]:
Books['B2']['authors'][1]
Out[34]:
{'first_name': 'Satish',
 'last_name': 'Panpaliya',
 'city': 'Chicago',
 'email': 'satish@gktcs.com'}
In [35]:
Books['B2']['authors'][1]['last_name']
Out[35]:
'Panpaliya'
In [36]:
Books['B2']['authors'][1]['last_name'] = 'Rathi'
In [38]:
Books['B2']['authors']
Out[38]:
[{'first_name': 'Narendra',
  'last_name': 'Panpaliya',
  'city': 'Pune',
  'email': 'narendra@gktcs.com'},
 {'first_name': 'Satish',
  'last_name': 'Rathi',
  'city': 'Chicago',
  'email': 'satish@gktcs.com'}]

Iterator / Generator

In [39]:
for var in ['data1','data2','data3']:
    print(var)
data1
data2
data3
In [40]:
list(range(1,25,2))
Out[40]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [44]:
# Generator are functions which create iterators. 

def gy(arg1, arg2):
    '''Generator Function'''
    yield arg1
    yield arg2
    yield arg1 + arg2
    yield arg1 - arg2
    yield arg1 * arg2
    yield arg1 / arg2
    yield arg1 % arg2
    yield arg1 ** arg2
    return

g1 = gy(10, 2)
g1
#dir(g1)
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
print(g1.__next__())
10
2
12
8
20
5.0
0
100
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-44-11ef4673c4b6> in <module>
     24 print(g1.__next__())
     25 print(g1.__next__())
---> 26 print(g1.__next__())
     27 
     28 

StopIteration: 
In [45]:
g2 = gy(20, 4)
for item in g2:
    print(item)
20
4
24
16
80
5.0
0
160000
In [46]:
g3 = gy(30, 4)
list(g3)
Out[46]:
[30, 4, 34, 26, 120, 7.5, 2, 810000]
In [47]:
def fibonacci(maxnum):
    '''Fibonacci of any number '''
    first, second = 0, 1  # parallel assignment 
    for i in range(0,maxnum):
        yield first
        first, second = second, first + second
        
f1 = fibonacci(20)

list(f1)
Out[47]:
[0,
 1,
 1,
 2,
 3,
 5,
 8,
 13,
 21,
 34,
 55,
 89,
 144,
 233,
 377,
 610,
 987,
 1597,
 2584,
 4181]

lambda

Lambda is annonymous single line mathematical function. 
It looks like mathematical expression. 
In [49]:
add = lambda arg1, arg2 : arg1 + arg2
In [50]:
add
Out[50]:
<function __main__.<lambda>(arg1, arg2)>
In [51]:
add(45, 23)
Out[51]:
68
In [52]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

filter

filter is a function which takes two arguments 
1. function itself
2. sequence ( list, tuple, str)

It return those values from sequence where function is True.
In [54]:
list(filter(lambda arg1 : arg1 % 2 !=0 and arg1 % 3 !=0, 
      range(2,25)))
Out[54]:
[5, 7, 11, 13, 17, 19, 23]
In [55]:
fun1 = lambda arg1 : arg1 % 2 !=0 and arg1 % 3 !=0
In [56]:
fun1(2)
Out[56]:
False
In [57]:
fun1(5)
Out[57]:
True
In [58]:
list(range(2,25))
Out[58]:
[2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24]

Assignment

Salary = [200000, 300000, 250000, 400000, 500000,
      600000, 100000, 50000, 20000 ]

Filter Salary Sequence with Salary greater than 20,000 
( thousand) and 
less than 300000 ( 3 lakh)
In [66]:
Salary = [200000, 300000, 250000, 400000, 500000,
          600000, 100000, 50000, 20000 ]

fun2 = lambda arg : arg > 20000 and arg < 300000

print(fun2(50000))

list(filter(fun2, Salary))
True
Out[66]:
[200000, 250000, 100000, 50000]

map

map is a function which takes two or more arguments 
1. function itself
2. One or more sequences ( list, tuple, str)
3. Number of arguments to function are the same as 
number of sequences.
4. Apply functions to one or more sequences
In [67]:
cube = lambda arg : arg**3

cube(3)
Out[67]:
27
In [68]:
list(map(cube, Salary))
Out[68]:
[8000000000000000,
 27000000000000000,
 15625000000000000,
 64000000000000000,
 125000000000000000,
 216000000000000000,
 1000000000000000,
 125000000000000,
 8000000000000]
In [70]:
Salary = [200000, 300000, 250000, 400000, 500000,
          600000, 100000, 50000, 20000 ]

Salary1 = [100000, 400000, 350000, 400000, 500000,
          600000, 100000, 50000, 70000 ]

list(map(lambda arg1, arg2 : arg1 + arg2 , Salary, Salary1))
Out[70]:
[300000, 700000, 600000, 800000, 1000000, 1200000, 200000, 100000, 90000]

Set

Set is unorder collection of unique and immutable objects.
In [77]:
Salary = [200000, 300000, 250000, 400000, 500000,
          600000, 100000, 50000, 20000, 300000, 250000, 400000 ]

Salary1 = [100000, 400000, 350000, 400000, 500000,
          600000, 100000, 50000, 70000, 300000, 250000, 400000]


S1 = set(Salary)
print(S1)

S2 = set(Salary1)
print(S2)


print("****** Union of Set****** \n")

print(S1.union(S2))

print("****** Union of Set bit wise ****** \n")

S3 = S1 | S2

print(S3)


print("\n ****** Intersection of Set****** \n")

print(S1.intersection(S2))

print("\n ****** Intersection of Set bit wise ****** \n")

print(S1 & S2)

print("\n ***** Super Set ******* \n ")

print(S3.issuperset(S1))

print("\n ***** Sub Set ******* \n ")

print(S1.issubset(S3))
{200000, 400000, 500000, 300000, 600000, 100000, 20000, 250000, 50000}
{100000, 500000, 400000, 600000, 300000, 350000, 50000, 70000, 250000}
****** Union of Set****** 

{200000, 400000, 500000, 300000, 600000, 100000, 20000, 250000, 50000, 350000, 70000}
****** Union of Set bit wise ****** 

{200000, 400000, 500000, 300000, 600000, 100000, 20000, 250000, 50000, 350000, 70000}

 ****** Intersection of Set****** 

{100000, 500000, 300000, 400000, 600000, 50000, 250000}

 ****** Intersection of Set bit wise ****** 

{100000, 500000, 300000, 400000, 600000, 50000, 250000}

 ***** Super Set ******* 
 
True

 ***** Sub Set ******* 
 
True

sorted function

In [78]:
sorted(S1)
Out[78]:
[20000, 50000, 100000, 200000, 250000, 300000, 400000, 500000, 600000]
In [79]:
sorted(S3)
Out[79]:
[20000,
 50000,
 70000,
 100000,
 200000,
 250000,
 300000,
 350000,
 400000,
 500000,
 600000]
In [80]:
sorted(S3, reverse = True)
Out[80]:
[600000,
 500000,
 400000,
 350000,
 300000,
 250000,
 200000,
 100000,
 70000,
 50000,
 20000]
In [81]:
sorted(Salary)
Out[81]:
[20000,
 50000,
 100000,
 200000,
 250000,
 250000,
 300000,
 300000,
 400000,
 400000,
 500000,
 600000]

reversed function

In [83]:
list(reversed(Salary))
Out[83]:
[400000,
 250000,
 300000,
 20000,
 50000,
 100000,
 600000,
 500000,
 400000,
 250000,
 300000,
 200000]
In [85]:
L1 = list(reversed('SUREDNRA'))
print(L1)
['A', 'R', 'N', 'D', 'E', 'R', 'U', 'S']
In [90]:
Str2 = ':'.join(L1)
print(Str2)
A:R:N:D:E:R:U:S
In [88]:
Str1 = ' '.join(L1)
print(Str1)
A R N D E R U S
In [91]:
List2 = Str2.split(':')
print(List2)
['A', 'R', 'N', 'D', 'E', 'R', 'U', 'S']

enumerate function

Auto Indexing sequence
In [95]:
list(enumerate(Salary,1))
Out[95]:
[(1, 200000),
 (2, 300000),
 (3, 250000),
 (4, 400000),
 (5, 500000),
 (6, 600000),
 (7, 100000),
 (8, 50000),
 (9, 20000),
 (10, 300000),
 (11, 250000),
 (12, 400000)]
In [99]:
print(list(enumerate('SURENDRA PANPALIYA',1)))

print("\n")

print(list(enumerate('GKTCS Innovations',1)))
[(1, 'S'), (2, 'U'), (3, 'R'), (4, 'E'), (5, 'N'), (6, 'D'), (7, 'R'), (8, 'A'), (9, ' '), (10, 'P'), (11, 'A'), (12, 'N'), (13, 'P'), (14, 'A'), (15, 'L'), (16, 'I'), (17, 'Y'), (18, 'A')]


[(1, 'G'), (2, 'K'), (3, 'T'), (4, 'C'), (5, 'S'), (6, ' '), (7, 'I'), (8, 'n'), (9, 'n'), (10, 'o'), (11, 'v'), (12, 'a'), (13, 't'), (14, 'i'), (15, 'o'), (16, 'n'), (17, 's')]
In [103]:
print(len(Salary))
print(sum(Salary))
print(max(Salary))
print(min(Salary))
12
3370000
600000
20000
In [104]:
list(zip(Salary, Salary1))
Out[104]:
[(200000, 100000),
 (300000, 400000),
 (250000, 350000),
 (400000, 400000),
 (500000, 500000),
 (600000, 600000),
 (100000, 100000),
 (50000, 50000),
 (20000, 70000),
 (300000, 300000),
 (250000, 250000),
 (400000, 400000)]
In [105]:
list(zip('SURENDRA', 'PANPALIYA'))
Out[105]:
[('S', 'P'),
 ('U', 'A'),
 ('R', 'N'),
 ('E', 'P'),
 ('N', 'A'),
 ('D', 'L'),
 ('R', 'I'),
 ('A', 'Y')]

List Comprehension

1. We write comprehensive script inside list 
2. We can extract or apply on sequence without using filter or map or lambda.
In [106]:
[ num for num in Salary ]
Out[106]:
[200000,
 300000,
 250000,
 400000,
 500000,
 600000,
 100000,
 50000,
 20000,
 300000,
 250000,
 400000]
In [108]:
[ num**2 for num in Salary ]
Out[108]:
[40000000000,
 90000000000,
 62500000000,
 160000000000,
 250000000000,
 360000000000,
 10000000000,
 2500000000,
 400000000,
 90000000000,
 62500000000,
 160000000000]
In [112]:
[ num for num in Salary if num > 20000 and num < 300000 ]
Out[112]:
[200000, 250000, 100000, 50000, 250000]
In [114]:
 [ num for num in range(2, 25) if num % 2 != 0 and num % 3 != 0 ]
Out[114]:
[5, 7, 11, 13, 17, 19, 23]
In [115]:
 [ (num, num**3) for num in range(2, 25) 
  if num % 2 != 0 and num % 3 != 0 ]
Out[115]:
[(5, 125),
 (7, 343),
 (11, 1331),
 (13, 2197),
 (17, 4913),
 (19, 6859),
 (23, 12167)]

List Comprehension Assignment

Try Nested for loop inside list .

Words = [ 'abc','def', 'ghi', 'jkl', 'mno', 'pqr' ]

['a','b','c',......'r' ]

Dictionary Comprehension

1. We write comprehensive script inside Dictionary
2. We can extract or apply on sequence without using filter or map or lambda.
In [117]:
Fruits
Out[117]:
{'o': 'orange', 'g': 'grape', 'name': 'Fruits_name'}
In [118]:
{ key : value for key, value in Fruits.items() }
Out[118]:
{'o': 'orange', 'g': 'grape', 'name': 'Fruits_name'}
In [119]:
{ value : key for key, value in Fruits.items() }
Out[119]:
{'orange': 'o', 'grape': 'g', 'Fruits_name': 'name'}
In [120]:
{ value.upper() : key.upper() for key, value in Fruits.items() }
Out[120]:
{'ORANGE': 'O', 'GRAPE': 'G', 'FRUITS_NAME': 'NAME'}
In [ ]: