MIT Python学习基础系列(一) - list

Lists
Ordered sequence of information, accessible by index
Denoted by [ ]
  • A list contains elements usually homogenous, not commonly contain mixed types
  • Elements can be changed -> mutable
  • Changing elements
    After the element is changed, it still points to the same object
  • Iterating over a list
 for i in L: 
     total += i

List operation

  • Add elements to end of list
L.append( )
  • Mutates the list

    Everything in python is an object, lists are objects
    Objects has functions and methods

    • Access this information by object_name.something()
  • Concatenate 2 lists L1.extend( [0, 6] )

    • Mutate with L.extend (some_list)
  • Remove

del ( L[index] ) #delete element at specific index
#removes element at end of list
#If no index is specified, removes the last element
#Or remove the element at the specified index

L.pop ( index) 
#removes a specific element
#Removes the first occurrence if the element occurs multiple times
#Returns error if the element is not in the list
L.remove (element)
  • Converts strings and back
#returns a list with every character from s in L
list(s) 

# split a string on a character parameter 
# if called without a parameter, splits on spaces
s.split( )      

#turn a list of characters into a string 
‘ ‘. join(L)  (‘_’.join(L) - > “a_b_c” )
  • reverse()

Mutation, Aliasing, Cloning

  • Lists in memory
  • Is an object in memory
  • Variable name points to object
  • Any variable pointing to that object is affected -> watch out the side effects

Aliases
append() has side effect
print is not ==

  • If two lists print the same thing, does not mean they are the same structure
  • Can test by mutating one and check

Cloning a list
Create a new list and copy every element

L2 = L1[:] #L2 is a copy of L1->different from L2 = L1

Sorting a list
Sort change the list, returns nothing
sorted() does not mutate list, must assign result to a variable
L.sort() changes L, sorted(L) gives a sorted version of L but L stays the same

Lists of lists of lists of…
Can have nested lists

Mutation and iteration

  • Avoid mutating a list as you are iterating over it
for e in L1: 
    if e in L2: L1.remove( e)
L1 = [1,2,3,4] L2 = [1,4,2,6]  -> L1 = [2,3,4]

When you remove 1 in L1, L1 changes and python will not see 2 in L1
Solution
Make a copy of L1 and iterate over L1_copy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值