๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Python

[Python] ๋ฆฌ์ŠคํŠธ ๊ด€๋ จ ํ•จ์ˆ˜

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 5.
๋ฐ˜์‘ํ˜•

๋ฌธ์ž์—ด๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ฆฌ์ŠคํŠธ ๋ณ€์ˆ˜ ์ด๋ฆ„ ๋’ค์— '.'๋ฅผ ๋ถ™์—ฌ์„œ ์—ฌ๋Ÿฌ ๊ฐ€์ง€ ๋ฆฌ์ŠคํŠธ ๊ด€๋ จ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ์— ์š”์†Œ ์ถ”๊ฐ€ (append)

>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]

append(x)๋Š” ๋ฆฌ์ŠคํŠธ์˜ ๋งจ ๋งˆ์ง€๋ง‰์— x๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ ์ •๋ ฌ (sort)

>>> a = [1, 4, 3, 2]
>>> a.sort()
>>> a
[1, 2, 3, 4]

sort ํ•จ์ˆ˜๋Š” ๋ฆฌ์ŠคํŠธ์˜ ์š”์†Œ๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•ด์ค€๋‹ค.

 

>>> a = ['a', 'c', 'b']
>>> a.sort()
>>> a
['a', 'b', 'c']

 

 

-๋ฆฌ์ŠคํŠธ ๋’ค์ง‘๊ธฐ (reverse)

>>> a = ['a', 'c', 'b']
>>> a.reverse()
>>> a
['b', 'c', 'a']

reverse ํ•จ์ˆ˜๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ์—ญ์ˆœ์œผ๋กœ ๋’ค์ง‘์–ด ์ค€๋‹ค. ์ด๋•Œ ๋ฆฌ์ŠคํŠธ ์š”์†Œ๋“ค์„ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•œ ๋‹ค์Œ ๋‹ค์‹œ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๊ทธ์ € ํ˜„์žฌ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ทธ๋Œ€๋กœ ๊ฑฐ๊พธ๋กœ ๋’ค์ง‘๋Š”๋‹ค.

 

 

-์œ„์น˜ ๋ฐ˜ํ™˜ (index)

>>> a = [1, 2, 3]
>>> a.index(3)   ← 3์€ ๋ฆฌ์ŠคํŠธ a์˜ ์„ธ ๋ฒˆ์งธ(a[2]) ์š”์†Œ
2
>>> a.index(1)   ← 1์€ ๋ฆฌ์ŠคํŠธ a์˜ ์„ธ ๋ฒˆ์งธ(a[0]) ์š”์†Œ
0

index(x) ํ•จ์ˆ˜๋Š” ๋ฆฌ์ŠคํŠธ์— x ๊ฐ’์ด ์žˆ์œผ๋ฉด x์˜ ์œ„์น˜ ๊ฐ’์„ ๋Œ๋ ค์ค€๋‹ค.

 

>>> a.index(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 0 is not in list

๊ฐ’ 0์€ a ๋ฆฌ์ŠคํŠธ์— ์กด์žฌํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ’ ์˜ค๋ฅ˜(ValueError)๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ์— ์š”์†Œ ์‚ฝ์ž… (insert)

insert(a, b)๋Š” ๋ฆฌ์ŠคํŠธ์˜ a๋ฒˆ์งธ ์œ„์น˜์— b๋ฅผ ์‚ฝ์ž…ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.

>>> a = [1, 2, 3]
>>> a.insert(0, 4)   ← a[0] ์œ„์น˜์— 4 ์‚ฝ์ž…
[4, 1, 2, 3]

0๋ฒˆ์งธ ์ž๋ฆฌ, ์ฆ‰ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ(a[0]) ์œ„์น˜์— ๊ฐ’ 4๋ฅผ ์‚ฝ์ž…ํ•˜๋ผ๋Š” ๋œป์ด๋‹ค.

 

>>> a.insert(3, 5)   ← a[3] ์œ„์น˜์— 5 ์‚ฝ์ž…
[4, 1, 2, 5, 3]

๋ฆฌ์ŠคํŠธ a์˜ a[3], ์ฆ‰ ๋„ค ๋ฒˆ์งธ ์š”์†Œ ์œ„์น˜์— ๊ฐ’ 5๋ฅผ ์‚ฝ์ž…ํ•˜๋ผ๋Š” ๋œป์ด๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ ์š”์†Œ ์ œ๊ฑฐ (remove)

>>> a = [1, 2, 3, 1, 2, 3]
>>> a.remove(3)
[1, 2, 1, 2, 3]

remove(x)๋Š” ๋ฆฌ์ŠคํŠธ์—์„œ ์ฒซ ๋ฒˆ์งธ๋กœ ๋‚˜์˜ค๋Š” x๋ฅผ ์‚ญ์ œํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค.

 

>>> a.remove(3)
[1, 2, 1, 2]

 

 

-๋ฆฌ์ŠคํŠธ ์š”์†Œ ๋„์ง‘์–ด๋‚ด๊ธฐ (pop)

>>> a = [1, 2, 3]
>>> a.pop()
3
>>> a
[1, 2]

pop()์€ ๋ฆฌ์ŠคํŠธ์˜ ๋งจ ๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ๋Œ๋ ค์ฃผ๊ณ  ๊ทธ ์š”์†Œ๋Š” ์‚ญ์ œํ•œ๋‹ค.

 

>>> a = [1, 2, 3]
>>> a.pop(1)
2
>>> a
[1, 3]

a.pop(1)์€ a[1]์˜ ๊ฐ’์„ ๋„์ง‘์–ด๋‚ธ๋‹ค. ๋‹ค์‹œ a๋ฅผ ์ถœ๋ ฅํ•ด๋ณด๋ฉด ๋„์ง‘์–ด๋‚ธ ๊ฐ’์ด ์‚ญ์ œ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ์— ํฌํ•จ๋œ ์š”์†Œ x์˜ ๊ฐœ์ˆ˜ ์„ธ๊ธฐ (count)

>>> a = [1, 2, 3, 1]
>>> a.count(1)
2

count(x)๋Š” ๋ฆฌ์ŠคํŠธ ์•ˆ์— x๊ฐ€ ๋ช‡ ๊ฐœ ์žˆ๋Š”์ง€ ์กฐ์‚ฌํ•˜์—ฌ ๊ทธ ๊ฐœ์ˆ˜๋ฅผ ๋Œ๋ ค์ฃผ๋Š” ํ•จ์ˆ˜์ด๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ ํ™•์žฅ (extend)

>>> a = [1, 2, 3]
>>> a.extend([4, 5])
>>> a
[1, 2, 3, 4, 5]
>>> b = [6, 7]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6, 7]

extend(x)์—์„œ x์—๋Š” ๋ฆฌ์ŠคํŠธ๋งŒ ์˜ฌ ์ˆ˜ ์žˆ์œผ๋ฉฐ ์›๋ž˜์˜ a ๋ฆฌ์ŠคํŠธ์— x ๋ฆฌ์ŠคํŠธ๋ฅผ ๋”ํ•˜๊ฒŒ ๋œ๋‹ค.

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€