Python MIT OCW Lec5 : Tuples, Lists, Aliasing, Mutability, Cloning

김재만·2023년 9월 19일
0

Python MIT OCW

목록 보기
5/9

배울 내용

  1. Introduce new compound data types
    : tuples
    : lists
  2. idea of aliasing
  3. idea of mutability
  4. idea of cloning

1. Tuples

  • An ordered sequence of elements, can mix element types
  • Can't change element values -> immutable
  • represented with parantheses
te = () # empty tuple
t = (2, "mit", 3)
print(t[0]) # 2
print((2, "mit", 3) + (5, 6)) # (2, "mit", 3, 5, 6)
print(t[1:2]) # ("mit", ) -> extra comma means a tuple with one element
print(t[1:3]) # ("mit", 3)
len(t) # 3
# t[1] = 4 # gives an error, can modify object (immutablility)
  • Conveniently used to swap variable values
temp = x
x = y
y = temp

# using tuple
(x, y) = (y, x)
  • Used to return more than one value from a function
def quotient_and_remainder (x, y) : 
  q = x // y # integer division
  r = x % y
  return (q, r)

(quot, rem) = quotient_and_remainder(4, 5)
print((quot, rem)) # (0, 4)
  • Can iterate over tuples
    : Assume that there is aTuple : ((ints, strings), (ints, strings), (ints, strings))
def get_data(aTuple) : 
  nums = ()
  words = ()
  for t in aTuple : 
    nums = nums + (t[0],)
    if t[1] not in words :
      words = words + (t[1],)
  min_n = min(nums)
  max_n = max(nums)
  unique_words = len(words)
  return (min_n, max_n, unique_words)

2. Lists

  • Ordered sequence of information, accessible by index
  • Denoted by square brackets, []
  • Elements are usually homogeneous but can contain mixed types
  • Mutable

Indices and Ordering

a_list  = [] # empty list
L = [2, 'a', 4, [1, 2]]
print(len(L)) # 4
print(L[0]) # 2
print(L[2] + 1) # 5
print(L[3]) # [1, 2]
# print(L[4]) # this code gives an error 
i = 2
print(L[i-1]) # a

Mutability

L = [2, 1, 3]
L[1] = 5
print(L) # [2, 5, 3]

Iterating over a List

  • Compute the sum of elements of a list
  • Like strings, can iterate over list elements directly
  • Compare two codes :
L = [2, 1, 3]

total = 0
for i in range(len(L)) : 
  total += L[i]
print(total) # 6
L = [2, 1, 3]

total = 0
for i in L : 
  total += i
print(total)
  • 두번째 코드가 더 Pythonic 하다.

Operations on Lists

들어가기 전에

  • Everything in Python is an object
  • Objects have data
  • Objects have methods and functions
  • Access this information by object_name.do_something()
  • 추후 Object Oriented Programming 에서 더 배운다.

L.append(element)

  • Add elements to end of list
L = [2, 1, 3]
L.append(5)
print(L) # [2, 1, 3, 5]

L.extend(some_list)

  • mutate list with L.extend(some_list)
L1 = [2, 1, 3]
L2 = [4, 5, 6]
L3 = L1 + L2
print(L3) # [2, 1, 3, 4, 5, 6]
print(L1) # [2, 1, 3]
print(L2) # [4, 5 ,6]
# Concatenation, L1 and L2 unchanged

L1.extend([0, 6])
print(L1) # [2, 1, 3, 0, 6]
# Mutated L1 to [2, 1, 3, 0, 6]

Removing Operations

  • del(L[index])
    : delete element at a specific index
  • L.pop()
    : remove element at the end of list, returns the removed element
  • L.remove(element)
    : remove a specific element
    : looks for the element and removes it
    : removes first occurrence
    : if element is not in list, gives an error
L = [2, 1, 3, 6, 3, 7, 0]

L.remove(2) 
print(L) # [1, 3, 6, 3, 7, 0]

L.remove(3)
print(L) # [1, 6, 3, 7, 0]

del(L[1])
print(L) # [1, 3, 7, 0]

x = L.pop()
print(x) # 0
print(L) # [1, 3, 7]

Convert Lists to Strings and back

  • list(s)
    : convert string to list, returns a list with evrty character from s an element L

  • s.split()
    : split a string on a character parameter
    : splits on spaces if called without a parameter

  • ''.join(L)
    : turn a list of characters into a string
    : can give a character in quotes to add char btw every element

s = "I<3 cs"
print(list(s)) # ['I', '<', '3', ' ', 'c', 's']
print(s.split('<')) # ['I', '3 cs']

L = ['a', 'b', 'c'] 
print(''.join(L)) # abc
print('_'.join(L)) # a_b_c

Sorting Operation

L = [9, 6, 0, 3]
print(sorted(L)) # returns sorted list, does not mutate # [0, 3, 6, 9]
L.sort() # mutates L, return None
print(L) # [0, 3, 6, 9]
L.reverse() # mutates L, return None
print(L) # [9, 6, 3, 0]

3. Aliasing

  • See this code
warm = ['red', 'yellow', 'oragnge']
hot = warm # aliasing
hot.append('pink')
print(hot) # ['red', 'yellow', 'oragnge', 'pink']
print(warm) # ['red', 'yellow', 'oragnge', 'pink']
  • Python tutor 를 이용해 그림으로 살펴보자.

    : warm과 hot은 같은 object를 가리킨다.

4. Cloning

  • Create a new list and copy every element
  • See this code
cool = ['blue', 'green', 'grey']
chill = cool[:]
chill.append('black')
print(chill) # ['blue', 'green', 'grey', 'black']
print(cool) # ['blue', 'green', 'grey']
  • 그림을 통해 살펴보자.

    : cool 과 chill은 서로 다른 object를 가리키게 된다.

  • sorted(L) 은 정렬된 리스트를 반환하며, 반환받은 변수는 다른 object를 가리키게 된다. 코드와 그림으로 확인해보자.

cool = ['grey', 'green', 'blue']
sortedcool = sorted(cool)
print(cool) # ['grey', 'green', 'blue']
print(sortedcool) # ['blue', 'green', 'grey']

5. Side effects of mutablility of lists

  • Side effects after mutation
    : See this code
warm = ['yellow', 'orange']
hot = ['red']
brightcolors = [warm]
brightcolors.append(hot)
print(brightcolors) # [['yellow', 'orange'], ['red']]
hot.append('pink')
print(hot) # ['red', 'pink']
print(brightcolors) # [['yellow', 'orange'], ['red', 'pink']]
  • 그림으로 확인해보자.

    : brightcolors는 warm과 hot을 다시 참조하기 때문에, warm과 hot이 mutate되면 영향을 받게 된다.

  • Iterate할 때 Mutate한다면 또다른 문제를 불러일으킨다.
    : Python uses an internal counter to keep track of index in the loop
    : Mutating changes the list length but Python doesn't updatae the counter
    : See this code

def remove_dups(L1, L2) :
  for e in L1 :
    if e in L2 :
      L1.remove(e)

L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
print(L1) # [2, 3, 4]
  • 원하는 결과는 [3, 4] 이지만 [2, 3, 4] 가 출력. 이유는 상술했던 것처럼 counter를 업데이트 하지 않기 때문이다. 이를 해결하기 위해서는 loop element를 위한 list를 cloning해야한다. 다음 코드를 보자.
def remove_dups(L1, L2) :
  L1_copy = L1[:]
  for e in L1_copy :
    if e in L2 :
      L1.remove(e)

L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
print(L1) # [3, 4]

: L1_copy를 loop element로 사용하여 문제를 해결하였다.

profile
Hardware Engineer가 되자

0개의 댓글