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

[Python] ๋ฆฌ์ŠคํŠธ ์ž๋ฃŒํ˜•

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

โ–ถ ๋ฆฌ์ŠคํŠธ๋Š” ์–ด๋–ป๊ฒŒ ๋งŒ๋“ค๊ณ  ์‚ฌ์šฉํ• ๊นŒ?

>>> odd = [1, 3, 5, 7, 9]

๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค ๋•Œ๋Š” ์œ„์—์„œ ๋ณด๋Š” ๊ฒƒ๊ณผ ๊ฐ™์ด ๋Œ€๊ด„ํ˜ธ([])๋กœ ๊ฐ์‹ธ ์ฃผ๊ณ  ๊ฐ ์š”์†Œ๊ฐ’์€ ์‰ผํ‘œ(,)๋กœ ๊ตฌ๋ถ„ํ•ด ์ค€๋‹ค.

 

 

-์—ฌ๋Ÿฌ ๊ฐ€์ง€ ๋ฆฌ์ŠคํŠธ์˜ ์ƒ๊น€์ƒˆ

>>> a = []
>>> b = [1, 2, 3]
>>> c = ['Life', 'is', 'too', 'short']
>>> d = [1, 2, 'Life', 'is']
>>> e = [1, 2, ['Life', 'is']]

์ฆ‰, ๋ฆฌ์ŠคํŠธ ์•ˆ์—๋Š” ์–ด๋– ํ•œ ์ž๋ฃŒํ˜•๋„ ํฌํ•จ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

 

 

 

โ–ถ ๋ฆฌ์ŠคํŠธ์˜ ์ธ๋ฑ์‹ฑ๊ณผ ์Šฌ๋ผ์ด์‹ฑ

-๋ฆฌ์ŠคํŠธ์˜ ์ธ๋ฑ์‹ฑ

์˜ˆ์‹œ 1)

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[0]
1
>>> a[0] + a[2]   ← 1 + 3
4
>>> a[-1]   ← ๋ฌธ์ž์—ด์˜ ๋งˆ์ง€๋ง‰ ์š”์†Œ๊ฐ’
3

 

 

์˜ˆ์‹œ 2)

>>> a = [1, 2, 3, ['a', 'b', 'c']]
>>> a[0]
1
>>> a[-1]
['a', 'b', 'c']
>>> a[3]
['a', 'b', 'c']

 

 

-๋ฆฌ์ŠคํŠธ a ์— ํฌํ•จ๋œ ['a', 'b', 'c'] ๋ฆฌ์ŠคํŠธ์—์„œ ๊ฐ’์„ ์ธ๋ฑ์‹ฑ์„ ์‚ฌ์šฉํ•ด ๋„์ง‘์–ด ๋‚ด๋Š” ๋ฐฉ๋ฒ•

>>> a[-1][0]
'a'
>>> a[-1][1]
'b'
>>> a[-1][2]
'c'

 

 

 

โ–ถ ๋ฆฌ์ŠคํŠธ์˜ ์Šฌ๋ผ์ด์‹ฑ

>>> a = [1, 2, 3, 4, 5]
>>> a[0:2]
[1, 2]
>>> a = "12345"
>>> a[0:2]
'12'

๋ฌธ์ž์—ด๊ณผ ์‚ฌ์šฉ๋ฒ•์ด ์™„์ „ํžˆ ๋™์ผํ•˜๋‹ค.

 

>>> a = [1, 2, 3, 4, 5]
>>> b = a[:2]   ← ์ฒ˜์Œ๋ถ€ํ„ฐ a[1]๊นŒ์ง€
>>> c = a[2:]   ← a[2]๋ถ€ํ„ฐ ๋งˆ์ง€๋ง‰๊นŒ์ง€
>>> b
[1, 2]
>>> c
[3, 4, 5]

 

 

 

โ–ถ ๋ฆฌ์ŠคํŠธ ์—ฐ์‚ฐํ•˜๊ธฐ

๋ฆฌ์ŠคํŠธ ์—ญ์‹œ + ๊ธฐํ˜ธ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋”ํ•  ์ˆ˜ ์žˆ๊ณ  * ๊ธฐํ˜ธ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฐ˜๋ณตํ•  ์ˆ˜ ์žˆ๋‹ค.

 

-๋ฆฌ์ŠคํŠธ ๋”ํ•˜๊ธฐ (+)

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]

๋ฆฌ์ŠคํŠธ ์‚ฌ์ด์—์„œ + ๊ธฐํ˜ธ๋Š” 2๊ฐœ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์น˜๋Š” ๊ธฐ๋Šฅ์„ ํ•œ๋‹ค.

 

 

-๋ฆฌ์ŠคํŠธ ๋ฐ˜๋ณตํ•˜๊ธฐ (*)

>>> a = [1, 2, 3]
>>> a * 3
[1, 2, 3, 1, 2, 3, 1 ,2, 3]

 

 

-๋ฆฌ์ŠคํŠธ ๊ธธ์ด ๊ตฌํ•˜๊ธฐ

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

 

 

 

โ–ถ ๋ฆฌ์ŠคํŠธ์˜ ์ˆ˜์ •๊ณผ ์‚ญ์ œ

-๋ฆฌ์ŠคํŠธ์—์„œ ๊ฐ’ ์ˆ˜์ •ํ•˜๊ธฐ

>>> a = [1, 2, 3]
>>> a[2] = 4
>>> a
[1, 2, 4]

 

 

-del ํ•จ์ˆ˜ ์‚ฌ์šฉํ•ด ๋ฆฌ์ŠคํŠธ ์š”์†Œ ์‚ญ์ œํ•˜๊ธฐ

>>> a = [1, 2, 3]
>>> del a[1]
>>> a
[1, 3]

del ํ•จ์ˆ˜๋Š” ํŒŒ์ด์ฌ์ด ์ž์ฒด์ ์œผ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์‚ญ์ œ ํ•จ์ˆ˜์ด๋‹ค.

 

 

>>> a = [1, 2, 3, 4, 5]
>>> del a[2:]
>>> a
[1, 2]

์Šฌ๋ผ์ด์‹ฑ ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ์˜ ์š”์†Œ ์—ฌ๋Ÿฌ๊ฐœ๋ฅผ ํ•œ๊บผ๋ฒˆ์— ์‚ญ์ œํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€