Mutation

把单独值装进列表 b=[199]  b[0]---199 

lst=[6,1,'b']                      lst----[6,1,'b']

lst[2]='a' (reasign a new value to the list)  lst ------[6,1,'a']

method call

1. append takes in a single element and adds a single element to the end of the list

lst.append(2)                  lst------[6,1,'a', 2] 

2. extend takes in a sequence of values or an iterable

lst.extend([0,1,9])           lst------[6,1,'a', 2, 0, 1, 9] 

3. insert takes in an index of the list and value to insert

lst.insert(3, 'summer')      lst------[6,1,'a', 'summer', 2, 0, 1, 9] 

### the return value of the above is none###

a=lst.append(7)

print(a) ---- None

new_lst = [1]

new_lst.extend(range(10))      new_lst ----- [ 1,0,1,2,3,4,5,6,7,8,9 ]

#nest list# 

new_lst = [1]  new_lst.append([1,2])      new_lst-----[1, [1,2]]

new_lst.insert(1, [3,4])                            new_list -----[1, [3,4], [1,2]]

4. pop to remove and returns the last element of that list # pop is the only methond that returns the elements that are removed# bc pop only pass in an index you don't actually know which element you are removing so it has to return it to let you know. For other methods you know which elements are you mutating so they return None. #

lst = [6,1,'a', 'summer', 2,0,1,9,7]

lst.pop -----7    lst----[6,1,'a', 'summer', 2,0,1,9] 

b = lst.pop(3)  lst----- [6,1,'a', 2,0,1,9]    b----''summer' # pass an index 3 this is going to remove the element at index 3, b contains the value that was popped off#

5. remove takes in an index, it removes the first occurrence of that element within the list

lst.remove(6) # remove the first 6 I see in the list#  lst----[1,'a', 2,0,1,9]

lst.remove(1)  lst---- ['a', 2,0,1,9]

if want to move all 1 in the list

while 1 in lst:

         lst. remove(1)

Mutate dictionaries (dictionaries doesn't have a sense of order, it doesn't matter where they exist in the dictionary, bc you only access it by looking up a specific key (don't look up values))

d={'M' : 'Alex'

      'W' : 'Tiffany'

      'Th': 'Chris'}

d['M'] ---- 'Alex'      d['Th']----'Chris'

d['T'] = 'Tiffany'       d  ----   {'T' : 'Tiffany', 'M' : 'Alex', 'Th' : 'Chris', 'W' : 'Tiffany'}

update the value:   d['W'] = 'Alex'         d ----     {'T' : 'Tiffany', 'M' : 'Alex', 'Th' : 'Chris', 'W' : 'Alex'}

'F' in d ---- Flase 

'W' in d --- True

d.itmes() ---- dict_items([( 'T', 'Tiffany'), ('M', 'Alex'), ('Th', 'Chris'), ('W', 'Alex')])

d.values() --- dict_valaues(['Tiffany', 'Alex', 'Chris', 'Alex'])

'Tiffany' in d.values() ---- True

d.keys() --- dict_keys(['T', 'M', 'Th', 'W'])

Build up a dictionary from scrach

 update a string--- create a new string

Tuple-- they are immutable, create new tuples, they aren't modigying the original tuple, cannot use append etc. It's does everything a list can do except for mutating it. 

t=(1,2,3,4)  t---(1,2,3,4)

t[2]=3

t[:1]---(1,)

def f():

       return (1,2)

x,y=f()   x---1,   y----2

Identity means that two variables point to the exact same object. 

<expr0> is <expr1> : evaluates to True if both <expr0> and <expr1> evaluate to the same object

Equality  <expr0> == <expr1>

evaluates to True if both <expr0> and <expr1> evaluates to equal values

if they point to the same thing, they have to point to the thing with equal value. 

but something can be equal even if it isn't identical. 

l1=[1,2,3]    l2=[1,2,3]    l1 is l2--- Flase  l1 == l2 ---- True

l3=l1    l3-----[1,2,3]    l3 == l2 True  (l1 and l3 are identical)

l1[0] = 0  l1 = l3 ----[0,2,3]  l2---[1,2,3]  

if you have two variable which are identical and you mutate one but didn't mean to mutate all identicals, this may cause problems. 

l1 = l2[:]  they are equal but not identical  l1==l2    l1 is l2---Flase

slicing always creates a copy of your list and creates a new list

If you mutate a nested list that's pointed to by multiple lists that change will be reflected in all of them. if you make a copy of a list and you have nested lists, mutating the nested lists will affact the copies as well. 

add one more element to list 1, that element will itself be a list bc list3 evaluates to this list, so add one element to the end of list1 which is going to point to this list 

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

list 2= list1 identical

list 3 = list1[:]

list1[0] = 10 ----- list1=list2=[10, [2,3], 4]

list3[2] = 40 ----- list3 = [1, [2,3], 40]

list2[1][1]=30  ----- list1=list2=[10, [2, 30],4] list3=[1, [2, 30], 40]  affect list3 bc it changes the nested list

list2.pop(1) ---- list2=list1=[10, 4]  does not affect list3

list1.append(list3) --- list1=list2=[10, 4, [1, [2, 30], 40]]  add one element to list1 will itself be a list

Non_local assignment & Persistent local state

def make_withdraw(balance):

      ### return a withdraw function with a starting balance###

        def withdraw(amount):

               nonlocal balance 

               if amount>balance:

                      return 'Insufficient funds'

               balance = balance - amount   #re-bind balance in the first non-local frame in which it was bound previously# 

               return balance

         return withdraw

### nonlocal means whatever I reassigned the value of balance or whenever I sign to balance, I won't make a new binding in my current frame but rather, I will go up to the frame for make withdraw and modify the binding there.  

if I have multiple parents like I have parent which has another parent frame which has a multiple parent frame, and all of them have a binding for balance. I'll just to go the first one I see. When you are reassigning a non local variable you've 

nonlocal关键字只能用于嵌套函数中,并且外层函数中定义了相应的局部变量,否则会发生错误 

Status      Effect   x=2

No nonlocal statment

'x' is not bound locally        

Create a new binding from name 'x' to object 2 in the first frame of the current environment

No nonlocal statement

'x' is bound locally        

re-bind name 'x' object 2 in the first frame of the current environment

nonlocal x

'x' is bound in a non-local frame       

re-bind 'x' to 2 in the first non-local frame of the current environment in which 'x' is bound

nonlocal  x

'x' is not bound in a non-local frame

SyntaxError: no binding for nonlocal 'x' found

*** nonlocal x

'x' is bound in a non-local frame

'x' also bound locally

SyntaxError: name 'x' is parameter and nonlocal

Two important things for nonlocal:  "x" has to be bound in a parent frame other than the global frame, and 'x' can't be bound in the current frame. you will modify a binding in the first parent frame and not in current frame

***i.e.  I'm in f2 and my parent is f1, if I have a binding for x in f1, but I also have a binding for x in f2 which usually happens if x is one of your parameters, that's the scenario

mutable values can be changed without a nonlocal statement 用列表表示时不需用nonlocal

def new_withdraw(balance):
    b=[balance]                             # Name bound outside of withdraw def#
    def withdraw(amount):
        if b[0]<amount:
            return 'insufficient fund'
        b[0] = b[0]- amount              # Element assignment changes a list#
        return b[0]
    return withdraw

output:

withdraw=new_withdraw(100)
withdraw(9)
91

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值