๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด/Python

ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ(list)์˜ ๋ชจ๋“  ๊ฒƒ

by ์„œ์•„๋ž‘๐Ÿ˜ 2023. 12. 2.

 

๋ฆฌ์ŠคํŠธ(list)

๋ฆฌ์ŠคํŠธ๋Š” ์ธ๋ฑ์Šค ๋ฐฉ์‹์˜ ์ˆœ์ฐจ ๋ฐฐ์—ด ์ปจํ…Œ์ด๋„ˆ์ž…๋‹ˆ๋‹ค. ๋ฉ”๋ชจ๋ฆฌ์— ์ผ๋ ฌ๋กœ(linear) ๋ฐฐ์น˜๊ฐ€ ๋˜๋ฉฐ ๋ฆฌ์ŠคํŠธ ๋‚ด ์š”์†Œ๋ฅผ ๋ณ€๊ฒฝ(mutable)ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ ํ•˜๋‚˜์˜ ๋ฆฌ์ŠคํŠธ ๋‚ด ์—ฌ๋Ÿฌ ํƒ€์ž…(type)์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ด์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์Šฌ๋ผ์ด์‹ฑ

a = [1,2,3,4,5]
a[0:2]    # [1,2] -> [0:2]๋ฉด ์ธ๋ฑ์Šค 0๋ถ€ํ„ฐ 1๊นŒ์ง€(2๋Š” ํฌํ•จ๋˜์ง€ ์•Š์Œ)
a[a:2]    # [1,2]
a[2:]    # [3,4,5]

 

์—ฐ์‚ฐ

a = [1,2,3]
b = [5,6,7]
a+b    # [1,2,3,5,6,7]

a*3    # [1,2,3,1,2,3,1,2,3] -> ๋ฆฌ์ŠคํŠธ ๋ฐ˜๋ณต

len(a)    # 3 -> ๋ฆฌ์ŠคํŠธ ๊ธธ์ด
del a[1]    # [1,3] -> ํŠน์ดํ•œ ์ ์€ delํ•จ์ˆ˜์ธ๋ฐ ์„ ์–ธ๋ฐฉ์‹์œผ๋กœ ์“ฐ๋„ค..

 

ํ•จ์ˆ˜

  1. ์š”์†Œ ์ถ”๊ฐ€(append)
a = [1,2]
a.append(3)    # [1,2,3]

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

 

2. ์ •๋ ฌ(sort)

a = [4,2,6,5,3]
a.sort()    # [3,4,5,6,7]

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

 

 

3. ๋’ค์ง‘๊ธฐ(reverse)

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

 

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

a = [1,2,3]
a.index(3)   # 2 -> 3์ด ์žˆ๋Š” ์œ„์น˜๋Š” a[2]์ด๋ฏ€๋กœ 2 ๋ฐ˜ํ™˜
a.index(1)   # 0 -> 1์ด ์žˆ๋Š” ์œ„์น˜๋Š” a[0]์ด๋ฏ€๋กœ 0 ๋ฐ˜ํ™˜
a.index(5)   # 5๋Š” ์—†๊ธฐ ๋•Œ๋ฌธ์— ์˜ค๋ฅ˜ ๋ฐœ์ƒ

 

5. ์š”์†Œ ์‚ฝ์ž…(insert)

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

 

6. ์š”์†Œ ์ œ๊ฑฐ(remove)

a = [1,2,3,1,2,3]
a.remove(3)   # [1,2,1,2,3] -> ๋ฆฌ์ŠคํŠธ์—์„œ ์ฒซ ๋ฒˆ์งธ๋กœ ๋‚˜์˜ค๋Š” ๊ฐ’์„ ์‚ญ์ œ

 

7. ์š”์†Œ pop

a = [1,2,3]
a.pop(1)    # 2 -> a[1] ๋„์ง‘์–ด๋ƒ„
print(a)    # [1,3]

 

8. ํŠน์ • ์š”์†Œ์˜ ๊ฐœ์ˆ˜(count)

a = [2,3,4,2]
a.count(2)    # 2 -> 2๊ฐ€ ๋‘ ๊ฐœ ์žˆ์Œ

b = [1,2,3,[4,5]]
b.count(4)    # 0 -> ๋ฆฌ์ŠคํŠธ ์•ˆ์˜ ๋ฆฌ์ŠคํŠธ๋Š” ๊ทธ ์ž์ฒด๊ฐ€ ์š”์†Œ
b.count([4,5])    # 1

 

9. ๋ฆฌ์ŠคํŠธ ์ด์–ด๋ถ™์ด๊ธฐ(extend)

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

b = [6,7,8]
a.extand(b)    # [1,2,3,4,5,6,7,8] -> a += b์™€ ๋™์ผ

๋Œ“๊ธ€