๋ฐ์ํ
โถ ๋ฆฌ์คํธ๋ ์ด๋ป๊ฒ ๋ง๋ค๊ณ ์ฌ์ฉํ ๊น?
>>> 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]
์ฌ๋ผ์ด์ฑ ๊ธฐ๋ฒ์ ์ฌ์ฉํ์ฌ ๋ฆฌ์คํธ์ ์์ ์ฌ๋ฌ๊ฐ๋ฅผ ํ๊บผ๋ฒ์ ์ญ์ ํ ์๋ ์๋ค.
๋ฐ์ํ
'Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ํํ ์๋ฃํ (0) | 2021.02.05 |
---|---|
[Python] ๋ฆฌ์คํธ ๊ด๋ จ ํจ์ (0) | 2021.02.05 |
[Python] ๋ฌธ์์ด ๊ด๋ จ ํจ์ (0) | 2021.02.05 |
[Python] ๋ฌธ์์ด ํฌ๋งคํ (0) | 2021.02.05 |
[Python] ๋ฌธ์์ด ์ธ๋ฑ์ฑ๊ณผ ์ฌ๋ผ์ด์ฑ (0) | 2021.02.05 |
๋๊ธ