Python/Fundamentals

list, string, tuple, dictionary, set (iterables)

metamong 2022. 8. 19.

** iterable의 대표 5가지 list, string, tuple, dictionary, set에 대해 깔끔히 정리해보려 한다!

** 파이썬의 대표 자료 저장 방식으로, 반드시 알아야 하는 개념! 꼭 숙지하도록 하자


1. list

* intro

대괄호 []로 묶어서 표시

list()로 list를 만들 수 있음

print(list(range(1,11))) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list('hello')) #['h', 'e', 'l', 'l', 'o']

 

→ []안에는 ,로 분리하여 여러 개 요소를 담을 수 있음

숫자, 문자열, 그리고 숫자와 문자를 섞은 모든 list 구현 가능(즉, 한 list 내에 다양한 data type이 들어가도 가능)

* list comprehension

→ 식으로 생성해서 생성된 것을 바로 list 결과물로 나타내는 것

 

list comprehension

Q. list comprehension? A. list 안에 for문(+if문)을 포함시켜 편리 & 직관적인 프로그래밍 짜기 [f(x) for x in nums] → filter condition 추가도 가능! (if문) [f(x) for x in nums if g(x)] → ex) list안에 있는 element들을 한

sh-avid-learner.tistory.com

* list 제어 함수

함수 설명 사용법 time complexity
append() list의 element를 마지막 위치에 추가 list.append(x) O(1)
extend() list에서 여러 item을 추가 list.extend(x) O(K) (K: item 개수)
insert() list의 해당 지정 위치에 요소 삽입 list.insert(i,x) O(N)
sort() /sorted() 오름차순 / 내림차순 정렬 list.sort()
list.sort(reverse=True)
sorted(list)
O(NlogN)
reverse() / reversed() 현재의 list를 거꾸로 뒤집기 list.reverse()
reversed(list0
O(N)
pop() list 제일 뒤의 항목을 빼내고 해당 항목 삭제 / 제거할 위치에 있는 element 제거 list.pop()
list.pop(i)
O(1) for pop()
O(N) for pop(i)
remove() 원하는 element를 삭제 list.remove(x) O(N)
count() 해당 element의 개수 반환 list.count(x) O(N)
index() list에 위치 값이 있으면 위치 값 반환 list.index(x) O(1)
len() list의 길이 반환 len(list) O(N)
clear() / del 주어진 list 삭제 list.clear() O(N)

※ append()

→ time complexity: O(1)

오직 한 개의 자료만 list에 넣을 수 있다.

→ list 자체를 추가해서 이중 list를 만들 수 있다(여기서 중요한 건, 2차원 list가 만들어진다는 점. 추가되는 list가 원래의 list 내부로 들어감)

a=[]
b=['a','b','c']

a.append(10) #[10]
b.append('d') # ['a', 'b', 'c', 'd']

a=[10,20]
a.append([50,60]) #[10, 20, [50, 60]]

※ extend()

→ time complexity: O(K)

→ 기존 list에서 새로운 list를 추가해도, append와 다르게 단일 1차원의 list로만 허용된다.

→  iterable을 추가할 때, iterable 내에 있는 모든 item들을 각각 element로 기존 list에 추가하는 함수

a=[10] 
a.extend([10,20]) #[10, 10, 20]
a.extend('hello') #[10, 10, 20, 'h', 'e', 'l', 'l', 'o']
a.extend((5,6)) #[10, 10, 20, 'h', 'e', 'l', 'l', 'o', 5, 6]

※ insert(i,x)

→ time complexity: O(N)

index i라는 위치에 x를 추가

→ 오직 1개의 item만 list에 넣을 수 있다.

ex) insert(0,x)는 list의 맨 앞에 x를 추가 / insert(len(list),x)는 list의 맨 뒤에 x를 추가

a=[1,2,4,5]
a.insert(2,3) #[1, 2, 3, 4, 5]

※ sort() / sorted()

→ time complexity: O(NlogN)

→ list 내에 모두 동일 자료형이어야 정렬 가능 (다른 자료형이면 사용 불가)

 

① list.sort()

→ list를 정렬하는 함수 (숫자는 오름차순, 문자열은 사전순 정렬(대문자가 소문자보다 먼저 정렬)))

→ 3개의 인자, cmp, key, reverse가 있으나 key와 reverse인자를 써서 정렬하는게 더 효율적

a=[3,6,1,2] #[1, 2, 3, 6]
b=['koala','giraffe','Zebra','Monkey','gazelle'] #['Monkey', 'Zebra', 'gazelle', 'giraffe', 'koala']
a.sort()
b.sort()

 

→ key인자를 통해서는 간단한 함수 구현을 통해 함수 내용에 맞게 정렬 (lambda 함수 적용)

l = ['a', 'B', 'c']
l.sort(key=lambda x: x.lower())

print(l) #['a', 'B', 'c']

 

※ lambda 함수 하단 포스팅 확인 ※

 

λ 표현식

🤘🏻 파이썬에서 λ 표현식을 이용하면 함수를 간단하게 작성할 수 있다. 즉, 특정한 기능을 수행하는 함수를 단 한 줄에 작성할 수 있다는 게 큰 특징 #lambda 표현식으로 구현한 더하기 함수 prin

sh-avid-learner.tistory.com

 

reverse값이 True라면 default 정렬과 반대 (숫자는 내림차순, 문자열은 사전의 반대순서 정렬)

a=[3,6,1,2] #[6, 3, 2, 1]
b=['koala','giraffe','Zebra','Monkey','gazelle'] #['koala', 'giraffe', 'gazelle', 'Zebra', 'Monkey']
a.sort(reverse=True)
b.sort(reverse=True)

 

② sorted()

→ sort()와 동일. 다만 in-place 함수가 아니므로, 정렬한 결과를 별도의 메모리에 저장하고 싶을 때 사용하는 정렬 함수

→ 마찬가지로 3개의 인자, cmp, key, reverse가 있으나 key와 reverse인자를 써서 정렬하는게 더 효율적

tuple, list, dictionary, set 모두 sorted()에 적용가능하나 반환형은 list

print(sorted((3, 1, 2))) #[1, 2, 3]
print(sorted([3, 1, 2])) #[1, 2, 3]
print(sorted({3, 1, 2})) #[1, 2, 3]

print(sorted('foobar')) #['a', 'b', 'f', 'o', 'o', 'r']

print(sorted({'a': 1, 'c': 3, 'b': 2})) #['a', 'b', 'c']

 

reverse값을 True로 하면, 위 정렬된 결과의 반대 정렬 결과 출력

 

→ 마찬가지로 key인자를 통해서도 lambda로 구현한 함수 결과에 맞게 정렬

print(sorted(['A', 'b', 'C'], key=lambda x: x.lower())) #['A', 'b', 'C']
print(sorted(((1, ), (1, 2, 3), (1, 2)))) #[(1,), (1, 2), (1, 2, 3)]
print(sorted(((9, ), (1, 2, 3), (1, 2)), key=lambda x: sum(x))) #[(1, 2), (1, 2, 3), (9,)]

※ reverse() / reversed()

→ time complexity: O(N)

→ reverse():  주어진 list를 그대로 반대로 정렬하는 함수 (in-place)

→ reversed(): 주어진 list를 반대로 정렬한 결과를 별도의 메모리에 저장 (in-place)

(reverse iterator를 반환하므로, 따로 for문을 돌려 각각의 결과를 출력)

l = [1, 2, 3]
l.reverse()
print(l) #[3, 2, 1]
 
p=[]
for i in reversed(l):
    p.append(i)
print(p) #[3, 2, 1]
print(l) #[1, 2, 3]

※ pop()

→ time complexity: O(1) for pop() / O(N) for pop(index)

주어진 index의 element 1개를 꺼내는 함수

print([1, 2, 3].pop()) #3
print([1, 2, 3].pop(1)) #2

※ remove()

→ time complexity: O(N)

→ 주어진 list에서 처음 나오는 value를 제거하는 함수 (두 번째 이후 나오는 value는 제거되지 않음)

l = [1, 2, 9, 0, 2, 3]
l.remove(2)
print(l) #[1, 9, 0, 2, 3]

※ count()

→ time complexity: O(N)

→ 주어진 list에서 원하는 element의 개수를 반환 (문자열 함수로도 count() 사용 - 하단 내용 참조)

print([1, 1, 2].count(1)) #2

※ index()

→ time complexity: O(1)

→ 주어진 list에서 가장 먼저 등장하는 element의 index를 반환한다.

print([1, 2, 3, 2, 2, 3].index(2)) #1

※ len()

→ time complexity: O(1)

→ 주어진 list의 길이 반환(iterable하다면 다른 iterable도 모두 len() 적용 가능 - 하단 내용 참조)

l=[2,3,4]
print(len(l)) #3

※ clear()

→ time complexity: O(N)

→ list의 모든 element 삭제

l=[2,3,4]
l.clear()
print(l) #[]

※ del

→ 원하는 index를 집어넣으면 index에 맞는 element가 삭제된다.

l=[2,3,4]
del l[0]
print(l) #[3, 4]

del l[1:2]
print(l) #[2, 4]

2. string

 

 

 

 

 

 

 

★ list.split() ★

 

str.split(sep=None, maxsplit=- 1)

 

'Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].'

 

 

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

 

 

★ list.split(' ') ★

 

→ 명시적으로 ' '인, 한 개의 공백만 넣었기 때문에, 두 개 이상의 공백이 있다면, 한 개의 공백을 기준으로만 분리했으므로, 나머지 한 개의 공백이 list에 들어간다.

 

# space 1, space 2, space 3
s = 'hello my  big   world'

# 구분자를 단일 스페이스로 지정
words = s.split(sep=' ')

print(words)
print(len(words))

#출력
#['hello', 'my', '', 'big', '', '', 'world']
#7

* 문자열>

- 큰 따옴표나 작은 따옴표를 이용해 초기화 (백슬래시를 사용해 원하는 만큼 큰 따옴표나 작은 따옴표 포함 가능)

- +를 이용해 문자열끼리 연결 가능

- *를 이용해 원하는 문자열을 여러 번 더할 수 있음

- list와 마찬가지로 indexing과 slicing 가능 (그러나 특정 index를 통해 원하는 위치의 값을 변경할 수는 없음)

 

 

→ 문자열 추가 확인

 

python intro. (02)

* python = interpreter 방식의 언어 ≫ interpreter 방식의 언어란, 몇 줄의 code를 입력 후 enter를 치면 해당 부분이 바로 실행되고 정상처리/에러 여부를 알 수 있는 대화형 프로그래밍 언어이다 ≫ 그

sh-avid-learner.tistory.com

* tuple>

 

* 주로 언제 사용할까?

 

서로 다른 성질의 데이터를 묶어서 관리해야 할 때

(예를 들어 최단 경로 알고리즘을 구할 때, (비용,노드번호)의 튜플 - 비용은 실수값, 노드번호는 정수형태로 다른 성질의 데이터를 묶어서 관리 가능!)

 

데이터의 나열을 해싱(Hasing)의 키 값으로 사용할 때 - 변경 불가라 key 자체로 사용
(튜플은 변경이 불가능하므로 리스트와 다르게 키 값으로 사용 가능)

 

③ 리스트보다 메모리를 효율적으로 사용해야 할 때

 

* 기타 내용

 

인덱싱과 슬라이싱은 list와 동일

한 개의 원소가 들어간 tuple을 생성할 때 (1,) 이렇게 만들어줘야 함

a=() #empty tuple1
a=tuple(0) #empty tuple2
l=[1,2]
a=tuple(l) #(1,2)

a=(1,2,3) #(1,2,3)
a=1,2,3 #(1,2,3)

a=1, #(1,)
a=(1) #1

a=tuple(range(10)) #(0,1,2,3,4,5,6,7,8,9)

a=(10,20,(30,40)) #(10,20,(30,40))

a=(1,2,'a','b') #(1,2,'a','b')

a=(1,2)
a[0]=3 #AttributeError

2. 사전 자료형

* dictionary>

 

** Hash Table을 이용하므로 데이터의 조회 및 수정에 있어서 O(1)의 시간에 처리 가능!

** key는 변경 불가능하고, 중복도 불가능하다는 점! 

 

→ 키 데이터만 뽑을 때는 keys() 함수, 값 데이터만 뽑을 때는 values() 함수 (list() 씌워서 list 반환)

 

* dictionary 제어 함수 정리

함수 설명 사용법
get() 항목 접근하기 dict.get(key)
del()
pop()
항목 삭제하기
항목 꺼내고 삭제하기
del(dict[key])
dict.pop(key)
items() 딕셔너리에 저장된 항목 dict.items()
keys() 딕셔너리에 저장된 key dict.keys()
values() 딕셔너리에 저장된 value dict.values()

3. 집합 자료형

 

- 집합) 중복 허용 x, 순서 x

- 데이터의 조회 및 수정 - O(1)의 시간으로 처리 가능

- 리스트, 문자열로 초기화하고 set() 함수 사용

 

- 합집합(|), 교집합(&), 차집합(-) 연산 가능

 

a={10,20,30}
b={20,40,60}

print(a&b) #{20}
print(a.intersection(b)) #{20}

print(a|b) #{10,20,30,40,60}
print(a.union(b)) #{10,20,30,40,60}

print(a-b) #{10,30}
print(b-a) #{40,60}
print(a.difference(b)) #{10,30}
print(b.difference(a)) #{40,60}

 

- 관련 함수

add()로 새로운 원소 1개 추가

update()로 새로운 원소 여러 개 추가 가능 ex) data.update([5,6])

remove()로 특정 값을 갖는 원소 삭제 ex) remove(3)

 

※ 종합) 사전 자료형과 집합 자료형은 sequence와 다르게 순서가 없기 때문에 indexing으로 원하는 값을 얻을 수 없다.
(따라서, 사전의 key값 또는 집합의 원소 element를 이용해 O(1)의 시간복잡도로 조회)


* 썸네일 출처) https://medium.com/nerd-for-tech/lists-ranges-and-tuples-in-python-d7bb7a267c99

* split() docu) https://docs.python.org/3/library/stdtypes.html

* split() & split(' ') 차이 참조 https://wellsw.tistory.com/206

'Python > Fundamentals' 카테고리의 다른 글

python standard libraries  (0) 2022.08.22
λ 표현식  (0) 2022.08.21
File/Exception/Log Handling  (0) 2022.07.14
python OOP  (0) 2022.07.07
Python Basics(2). (from Coursera)  (0) 2022.04.13

댓글