Lists

  • Sequential, Ordered Collection
  • Creating lists

    
    
    In [1]:
    x = [4,2,6,3] #Create a list with values
    y = list() # Create an empty list
    y = [] #Create an empty list
    print(x)
    print(y)
    
    
    
    
    [4, 2, 6, 3]
    []
    

    Adding items to a list

    
    
    In [2]:
    x=list()
    print(x)
    x.append('One') #Adds 'One' to the back of the empty list
    print(x)
    x.append('Two') #Adds 'Two' to the back of the list ['One']
    print(x)
    
    
    
    
    []
    ['One']
    ['One', 'Two']
    
    
    
    In [3]:
    x.insert(0,'Half') #Inserts 'Half' at location 0. Items will shift to make roomw
    print(x)
    
    
    
    
    ['Half', 'One', 'Two']
    
    
    
    In [10]:
    x=list()
    x.extend([1,2,3]) #Unpacks the list and adds each item to the back of the list
    print(x)
    x.extend([4, 5])
    print(x)
    x.append([7,8])
    print(x)
    
    
    
    
    [1, 2, 3]
    [1, 2, 3, 4, 5]
    [1, 2, 3, 4, 5, [7, 8]]
    

    Indexing and slicing

    
    
    In [5]:
    x=[1,7,2,5,3,5,67,32]
    print(len(x))
    print(x[3])
    print(x[2:5])
    print(x[-1])
    print(x[::-1])
    
    
    
    
    8
    5
    [2, 5, 3]
    32
    [32, 67, 5, 3, 5, 2, 7, 1]
    

    Removing items from a list

    
    
    In [6]:
    x=[1,7,2,5,3,5,67,32]
    x.pop() #Removes the last element from a list
    print(x)
    x.pop(3) #Removes element at item 3 from a list
    print(x)
    x.remove(7) #Removes the first 7 from the list
    print(x)
    
    
    
    
    [1, 7, 2, 5, 3, 5, 67]
    [1, 7, 2, 3, 5, 67]
    [1, 2, 3, 5, 67]
    

    Anything you want to remove must be in the list or the location must be inside the list

    
    
    In [7]:
    x.remove(20)
    
    
    
    
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-7-c1262597e831> in <module>()
    ----> 1 x.remove(20)
    
    ValueError: list.remove(x): x not in list

    Mutablility of lists

    
    
    In [11]:
    y=['a','b']
    x = [1,y,3]
    print(x)
    print(y)
    y[1] = 4
    print(y)
    
    
    
    
    [1, ['a', 'b'], 3]
    ['a', 'b']
    ['a', 4]
    
    
    
    In [12]:
    print(x)
    
    
    
    
    [1, ['a', 4], 3]
    
    
    
    In [13]:
    x="Hello"
    print(x,id(x))
    x+=" You!"
    print(x,id(x)) #x is not the same object it was
    y=["Hello"]
    print(y,id(y))
    y+=["You!"] 
    print(y,id(y)) #y is still the same object. Lists are mutable. Strings are immutable
    
    
    
    
    Hello 4410984912
    Hello You! 4411850544
    ['Hello'] 4410131720
    ['Hello', 'You!'] 4410131720
    
    
    
    In [16]:
    def eggs(item,total=0):
        total+=item
        return total
    
    
    def spam(elem,some_list=[]):
        some_list.append(elem)
        print(id(some_list))
        return some_list
    
    
    
    In [17]:
    print(eggs(1))
    print(eggs(2))
    
    print(spam(1))
    print(spam(2))
    
    
    
    
    1
    2
    4411903304
    [1]
    4411903304
    [1, 2]
    

    Iteration

    Range iteration

    
    
    In [18]:
    #The for loop creates a new variable (e.g., index below)
    #range(len(x)) generates values from 0 to len(x) 
    x=[1,7,2,5,3,5,67,32]
    for index in range(len(x)):
        print(x[index])
    
    
    
    
    1
    7
    2
    5
    3
    5
    67
    32
    
    
    
    In [19]:
    list(range(len(x)))
    # generator 好处: 节省内存. 如果需要创建一个1billion 的数组, 可以使用这个来创建计数器.
    
    
    
    
    Out[19]:
    [0, 1, 2, 3, 4, 5, 6, 7]

    List element iteration

    
    
    In [20]:
    x=[1,7,2,5,3,5,67,32]
    for element in x: #The for draws elements - sequentially - from the list x and uses the variable "element" to store values
        print(element)
    
    
    
    
    1
    7
    2
    5
    3
    5
    67
    32
    

    Practice problem

    Write a function search_list that searches a list of tuple pairs and returns the value associated with the first element of the pair

    
    
    In [39]:
    def search_list(list_of_tuples,value):
        #Write the function here
        result = 0
        for item in list_of_tuples:
            if item[0] == value:
                return item[1]
        return result
    
    
    
    In [40]:
    prices = [('AAPL',96.43),('IONS',39.28),('GS',159.53)]
    ticker = 'IONS'
    print(search_list(prices,ticker))
    ticker = 'ION'
    print(search_list(prices,ticker))
    
    
    
    
    39.28
    0
    

    Dictionaries

    
    
    In [61]:
    mktcaps = {'AAPL':538.7,'GOOG':68.7,'IONS':4.6}
    
    
    
    In [62]:
    mktcaps['AAPL'] #Returns the value associated with the key "AAPL"
    
    
    
    
    Out[62]:
    538.7
    
    
    In [63]:
    mktcaps['GS'] #Error because GS is not in mktcaps
    
    
    
    
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-63-40312c94d4cd> in <module>()
    ----> 1 mktcaps['GS'] #Error because GS is not in mktcaps
    
    KeyError: 'GS'
    
    
    In [64]:
    mktcaps.get('GS') #Returns None because GS is not in mktcaps
    
    
    
    In [65]:
    mktcaps['GS'] = 88.65 #Adds GS to the dictionary
    print(mktcaps)
    
    
    
    
    {'GOOG': 68.7, 'GS': 88.65, 'IONS': 4.6, 'AAPL': 538.7}
    
    
    
    In [66]:
    del(mktcaps['GOOG']) #Removes GOOG from mktcaps
    print(mktcaps)
    
    
    
    
    {'GS': 88.65, 'IONS': 4.6, 'AAPL': 538.7}
    
    
    
    In [47]:
    mktcaps.keys() #Returns all the keys
    
    
    
    
    Out[47]:
    dict_keys(['GS', 'IONS', 'AAPL'])
    
    
    In [59]:
    mktcaps.values() #Returns all the values
    
    
    
    
    Out[59]:
    dict_values([88.65, 4.6, 538.7])
    
    
    In [52]:
    sorted(mktcaps.keys())
    
    
    
    
    Out[52]:
    ['AAPL', 'GS', 'IONS']
    
    
    In [69]:
    sorted(mktcaps.values())
    
    
    
    
    Out[69]:
    [4.6, 88.65, 538.7]
    
    
    In [70]:
    print(mktcaps)
    
    
    
    
    {'GS': 88.65, 'IONS': 4.6, 'AAPL': 538.7}
    
    
    
    In [86]:
    test = {'x':1, 'x':2, 'y':3}
    
    
    
    In [87]:
    test['x']
    
    
    
    
    Out[87]:
    2
    
    
    In [88]:
    for item in test:
        print(item[0])
    
    
    
    
    x
    y
    
    
    
    In [89]:
    len(test)
    
    
    
    
    Out[89]:
    2

    Sets

    
    
    In [90]:
    tickers = {"AAPL", "GE", "NFLX", "IONS"}
    regions = {"North East", "South", "West coast", "Mid-West"}
    
    
    
    In [91]:
    "AAPL" in tickers
    
    
    
    
    Out[91]:
    True
    
    
    In [92]:
    "IBK" in tickers
    
    
    
    
    Out[92]:
    False
    
    
    In [109]:
    pharma_tickers = {"IONS", "IMCL"}
    tickers.isdisjoint(pharma_tickers) # empty intersection 是否0交集
    
    
    
    
    Out[109]:
    False
    
    
    In [110]:
    tickers & pharma_tickers # intersection 交集
    
    
    
    
    Out[110]:
    {'IONS'}
    
    
    In [111]:
    tickers | pharma_tickers # union 并集
    
    
    
    
    Out[111]:
    {'AAPL', 'GE', 'IMCL', 'IONS', 'NFLX'}
    
    
    In [112]:
    tickers - pharma_tickers # set diference 不同
    
    
    
    
    Out[112]:
    {'AAPL', 'GE', 'NFLX'}
    
    
    In [113]:
    tickers > pharma_tickers # superset 是否为父集合
    
    
    
    
    Out[113]:
    False
    
    
    In [114]:
    pharma_tickers <= tickers # subset 是否为子集合
    
    
    
    
    Out[114]:
    False
    
    
    In [115]:
    pharma_tickers < tickers # proper-subset 是否为子集合
    
    
    
    
    Out[115]:
    False
    
    
    In [121]:
    for item in tickers:
        print(item)
    
    
    
    
    AAPL
    NFLX
    IONS
    GE
    
    
    
    In [126]:
    s = {1, 2, 4, 3}
    s[3] - 4
    
    
    
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-126-e3ade4c98af1> in <module>()
          1 s = {1, 2, 4, 3}
    ----> 2 s[3]
    
    TypeError: 'set' object does not support indexing
    
    
    In [122]:
    dict1 = {"john":40, "peter":45}
    dict2 = {"john":466, "peter":45}
    dict1 > dict2
    
    
    
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-122-5def35183ff3> in <module>()
          1 dict1 = {"john":40, "peter":45}
          2 dict2 = {"john":466, "peter":45}
    ----> 3 dict1 > dict2
    
    TypeError: unorderable types: dict() > dict()
    
    
    In [124]:
    del dict1["john"]
    
    
    
    In [125]:
    dict1
    
    
    
    
    Out[125]:
    {'peter': 45}
    
    
    In [ ]: