Skip to content

Latest commit

 

History

History
96 lines (76 loc) · 3.85 KB

File metadata and controls

96 lines (76 loc) · 3.85 KB

CHAPTER 2 An array of sequences

chapter2 array of sequences
1 Overview of built-in sequences
2 List comprehensions and generator expressions
3 Tuples are not just immutable lists
4 Slicing
5 Using + and * with sequences
6 Augmented assignment with sequences
7 list.sort and the sorted built-in function
8 Managing ordered sequences with bisect
9 When a list is not the answer

Container sequences and Flat sequences

flat sequences physically store the value of each item within its own memory space,limited to holding primitive values (str, bytes, bytearray, memoryview , array.array)

Container sequences hold references to the objects they contain,(list, tuple and collections.deque)

List comprehensions and generator expressions

A quick way to build a sequence is using a list comprehension(while using list) or a generator expression( except list)

symbols = '$¢£¥€¤'
codes = [ord(symbol) for symbol in symbols]
codes

Comprehension이란 iterable한 오브젝트를 생성하기 위한 방법중 하나로 파이썬에서 사용할 수 있는 유용한 기능중 하나이다. list comprehension은 항목을 필터링 및 변화함을 통해 반복가능한 자료형으로부터 리스트를 만든다.

  • List Comprehension (LC)
  • Set Comprehension (SC)
  • Dict Comprehension (DC)
  • Generator Expression (GE)
evens = [x * 2 for x in range(11)]
# 20까지의 짝수를 출력하기 위해 다음과 같은 LC를 사용할 수 있다

# 다음의 LC는 중복된 값들을 포함한다
no_primes = [j for i in range(2, 9) for j in range(i * 2, 50, i)]
# SC를 사용하면 중복값이 없는 집합을 얻을 수 있다
no_primes = {j for i in range(2, 9) for j in range(i * 2, 50, i)}

# 두 리스트를 하나의 dict로 합치는 DC. 하나는 key, 또 다른 하나는 value로 사용한다
subjects = ['math', 'history', 'english', 'computer engineering']
scores = [90, 80, 95, 100]
score_dict = {key: value for key, value in zip(subjects, scores)}

# Generator expression은 특별한 형태의 comprehension이다. 이는 한 번에 모든 원소를 반환하지 않고 한 번에 하나의 원소만 반환하는 generator를 생성한다.대괄호 대신 괄호 사용 
gen = (x**2 for x in range(10))
print(gen)
print(next(gen))
반복자 프로토콜을 이용하여 항목을 하나씩 생성해 메모리를 더 적게 사용하는 장점

Tuples are not just immutable lists

a = (1, 2, [1, 2, 3])

print(a)
id_1 = a[-1]

a[-1].append(1000)

print(a)
id_2 = a[-1]

print(id_1 == id_2)

# (1, 2, [1, 2, 3])
#(1, 2, [1, 2, 3, 1000])
#True

mutable object 와 immutable object

  • mutable object -- list, dictionary, set
  • immutable object -- integer, string, tuple
  • container=Some objects contain references to other objects; these are called containers.

  • 다른 객체의 참조(reference)를 담고있는 객체를 컨테이너(container)라고 부른다.

  • 컨테이너에는 리스트(list), 딕셔너리(dictionary), 튜플(tuple), 집합(set) 등이 있다.

  • 위 튜플에서 참조하고 있는 리스트이 값이 변경됐다 ‘튜플은 어떤 값을 포함하고 있는가’

  • 튜플은 불변 객체이면서 컨테이너이다. 다시 말해서, 튜플은 다른 객체의 참조를 담고 있다. 튜플이 불변 객체라 하는 것은 이 참조들이 변경되지 않는다는 의미이다. 튜플이 담고 있는 참조가 불변이라고 해서 참조된 객체의 값 역시 불변이라는 것을 의미하지 않는다. 만약, 리스트나 딕셔너리처럼 가변 객체일 경우에는 위의 코드처럼 참조된 객체의 값이 변경될 수 있다.