Sudhir Tuple List set Dict SCU

Docstrings

In [70]:
def donothingU(value):
    """ RI will give you what you gave me"""
    return value
In [71]:
help(donothingU)
Help on function donothingU in module __main__:

donothingU(value)
    RI will give you what you gave me

In [59]:
#Docstrings uses tripple quotation marks and shows in help
In [72]:
def squareU(value):
    """ 
    
    (c) Sudhir Wadhwa 
    Palo Alto, Ca
    
    Returns the square of a value"""
    return value**2
In [73]:
help(squareU)
Help on function squareU in module __main__:

squareU(value)
    (c) Sudhir Wadhwa 
    Palo Alto, Ca
    
    Returns the square of a value

In [74]:
squareU(16)
Out[74]:
256

Tuple

In [75]:
#Tuple is immutable - you cannot modify vales in a Tuple
# Tuple is constructed using parantheses ()
Even = (2,4,6,8)
In [76]:
print (type(Even))
<class 'tuple'>
In [77]:
#unpack Tuple 
# assigning elemnts of Tuple 
w,x,y,z = Even
In [78]:
print (z)
8
In [79]:
# get an elment of a Tuple
print (Even[3])
8
In [81]:
# Accept mutiple valuse and returing multiple values

def squareBoth(value1, value2):
    """ Returns the square of a value1 with 
    value 2 AND Vice versa"""
    
    new_value1 = value1 ** value2
    new_value2 = value2 ** value1
    
    # Constucting a Tuple 
    result = (new_value1,new_value2)
    
    return result
In [82]:
help(squareBoth)
Help on function squareBoth in module __main__:

squareBoth(value1, value2)
    Returns the square of a value1 with 
    value 2 AND Vice versa

In [83]:
# 4 ** 5
# 5 ** 4

squareBoth(4,5)
Out[83]:
(1024, 625)
Think Tuple as row - a record you are PACKING bunch of values togeather
In [84]:
t1 = ("goog","2017-08-09", 200, 300.34)
In [85]:
type(t1)
Out[85]:
tuple
In [86]:
t1[0]
Out[86]:
'goog'
In [87]:
t1[2]*t1[3]
Out[87]:
60067.99999999999
we can UNPACK the values
In [88]:
ticker , date , shares, price = t1
In [89]:
ticker
Out[89]:
'goog'
In [20]:
price
Out[20]:
300.34
Tuples are immutable , once created , its frozen The difference between list and tuple is that list is mutable while tuple is not.
In [91]:
t1
Out[91]:
('goog', '2017-08-09', 200, 300.34)
In [90]:
t1[3]
Out[90]:
300.34
In [92]:
# lets try to change the element in a Tuple 
# Tuple does not support assignment
t1[3] = 400.99
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-92-e3017c61e357> in <module>()
      1 # lets try to change the element in a Tuple
      2 # Tuple does not support assignment
----> 3 t1[3] = 400.99

TypeError: 'tuple' object does not support item assignment
In [93]:
# You can count elements in a Tuple

names = ("nancy","john","adam","nancy","kim","nancy")
# count how many nancy

countNancy = names.count('nancy')

print('The count of Nancy is:', countNancy)
The count of Nancy is: 3

List

In [94]:
bayCompany = ["cisco", "yahoo", "google"]
In [95]:
type(bayCompany)
Out[95]:
list
In [96]:
len(bayCompany)
Out[96]:
3
In [97]:
# List is mutable - can change , append 
bayCompany.append("facebook")
In [27]:
bayCompany
Out[27]:
['cisco', 'yahoo', 'google', 'facebook']
In [98]:
len(bayCompany)
Out[98]:
4
lists are mutable - you can modify usually with lists - all items are of same type
In [99]:
# Insert at 2nd position 
bayCompany.insert(2,"twitter")
In [100]:
bayCompany
Out[100]:
['cisco', 'yahoo', 'twitter', 'google', 'facebook']
In [101]:
len(bayCompany)
Out[101]:
5
In [102]:
# list element can be changed
bayCompany[1] = "IBM"
In [103]:
bayCompany
Out[103]:
['cisco', 'IBM', 'twitter', 'google', 'facebook']

Set

set is collection of distinct objects
In [106]:
unique_name = {'cisco', 'yahoo', 'twitter', 'google', 'facebook','twitter','cisco' }
In [107]:
unique_name
Out[107]:
{'cisco', 'facebook', 'google', 'twitter', 'yahoo'}
In [108]:
routerNames = ["uk","sj","sd","pg","ir","uk","uk"]
In [109]:
type(routerNames)
Out[109]:
list
In [110]:
routerNames
Out[110]:
['uk', 'sj', 'sd', 'pg', 'ir', 'uk', 'uk']
In [111]:
# You can use set to get unique router names here 
uniqueRouters = set(routerNames)
In [112]:
type(uniqueRouters)
Out[112]:
set
In [113]:
uniqueRouters
Out[113]:
{'ir', 'pg', 'sd', 'sj', 'uk'}
In [116]:
if "ir" in uniqueRouters:
    print ("Router found")
    
    
Router found

You are given 2 Lists

  • List of Routers : givenListOfRouters
  • routerMaster : Master List

Your goal is to find if routers in givenListOfRouters exist in routerMaster

In [117]:
givenListOfRouters = ['jp', 'ml', 'sj', 'pg', 'uk', 'tw']
routerMaster = ['uk', 'sj', 'sd', 'pg', 'ir', 'uk', 'uk','as','ml','in','cn']

Step 1 : Create a unique set from this given list; there might be duplicates

In [118]:
uniqueRouterFromrouterMaster = set(routerMaster)
uniqueRouterFromrouterMaster
Out[118]:
{'as', 'cn', 'in', 'ir', 'ml', 'pg', 'sd', 'sj', 'uk'}

Step 2: Loop all rtrs given in givenListOfRouters and check one by one if this rtr exixts in MasterList, if it exists , we will say this is our router , else we will say not our router.

We will use enumerate : enumerate allows us to loop over something and have an automatic counter. In this case rownum is the automatic counter.

In [119]:
for rownum, rtr in enumerate(givenListOfRouters, start =1):
    if rtr in uniqueRouterFromrouterMaster:
        print (rownum,rtr, "is our router")
    else:
        print (rownum,rtr, "is not our router")
1 jp is not our router
2 ml is our router
3 sj is our router
4 pg is our router
5 uk is our router
6 tw is not our router

Dict

In [49]:
a = {
        "username" : "sudhir",
        "home" : "/home/sudhir",
        "uid" : 920
    }
type(a)
Out[49]:
dict
In [50]:
# To access members of a dictionary, use the key-indexing operator as follows:

u = a["username"]
h = a["home"]
print (u,h)
sudhir /home/sudhir
In [51]:
# Inserting or modifying

a["username"] = "sach"
a["home"] = "/home/sach"
a["uid"] = 922
a["shell"] = "/usr/bin/tcsh"
In [52]:
#Although strings are the most common type of key, 
# you can use many other Python objects, including numbers 
# and tuples. Some objects, including lists and dictionaries, 
# cannot be used as keys, 
# because their contents are allowed to change.

a
        
        
Out[52]:
{'home': '/home/sach',
 'shell': '/usr/bin/tcsh',
 'uid': 922,
 'username': 'sach'}
In [53]:
myDiction = {"AMZN":1126.31, "AAPL": 169.98, "TSLA":308.74,"NELX":194.10}
In [54]:
type(myDiction)
Out[54]:
dict
In [55]:
myDiction["TSLA"]
Out[55]:
308.74
In [56]:
for rownum, ticker in enumerate(myDiction, start=1):
    print (rownum, ticker)
1 AMZN
2 AAPL
3 TSLA
4 NELX
In [107]:
"TSLA" in myDiction
Out[107]:
True
In [108]:
"CSCO" in myDiction
Out[108]:
False

Nesting

In [57]:
myDiction2 = {
    "AMZN": { "current": 1126.31, "low":78, "high" :1200},
    "AAPL": 169.98, 
    "TSLA":308.74,
    "NELX":{ "current": 116.90, "low":10, "high" :2200}
             }
In [58]:
myDiction2["TSLA"]
Out[58]:
308.74
In [59]:
myDiction2["AMZN"]
Out[59]:
{'current': 1126.31, 'high': 1200, 'low': 78}
In [60]:
myDiction2["AMZN"]["low"]
Out[60]:
78
In [115]:
myDiction2["NELX"]["high"]
Out[115]:
2200
In [61]:
myStudents = {
    "Nancy": { "twitter": 
              "Dir of OPS", 
              "Yahoo":
              "Ops Manager"},
    
    "John": { "twitter": 
             "VP OPS", 
             "Yahoo":"IT Manager"}
}
In [62]:
myStudents
Out[62]:
{'John': {'Yahoo': 'IT Manager', 'twitter': 'VP OPS'},
 'Nancy': {'Yahoo': 'Ops Manager', 'twitter': 'Dir of OPS'}}
In [63]:
myStudents2 = {
    "Nancy": { "twitter": 
              {"Dir of OPS", 150000}, 
              "Yahoo":
              "Ops Manager"},
"John": { "twitter": 
             "VP OPS", 
             "Yahoo":"IT Manager"}
}
In [64]:
type(myStudents2)
Out[64]:
dict
In [65]:
myStudents2["Nancy"]
Out[65]:
{'Yahoo': 'Ops Manager', 'twitter': {150000, 'Dir of OPS'}}
In [66]:
myStudents2["Nancy"]["twitter"]
Out[66]:
{150000, 'Dir of OPS'}