List (๋ฆฌ์คํธ)
: ์ฌ๋ฌ ๊ฐ์ ๊ฐ์ ์์๋๋ก ์ ์ฅํ๋ ๋ณ๊ฒฝ ๊ฐ๋ฅํ ์ํ์ค ์๋ฃํ
๋ฆฌ์คํธ์ ํน์ง
- ์์๊ฐ ์กด์ฌ
- ๊ฐ๋ณํ ์๋ฃํ
- ๋๊ดํธ([])๋ก ํ๊ธฐ
- ์ด๋ค ์๋ฃํ์ด๋ผ๋ ์ ์ฅ ๊ฐ๋ฅ
- 0 ๊ฐ ์ด์์ ๊ฐ์ฒด๋ฅผ ํฌํจํ๋ฉฐ ๋ฐ์ดํฐ ๋ชฉ๋ก์ ์ ์ฅ
my_list_1 = [1, 'a', 3, 'b', 5]
my_list_2 = [1, 2, 3, 'Python', ['hello', 'world', '!!!']]
> ๋น์ด์๋ ๋ฆฌ์คํธ ์์ฑ
a = list()
b = []
๋ฆฌ์คํธ์ ์ธ๋ฑ์ฑ( indexing )
my_list = [1, 'a', 3, 'b', 5]
print(my_list[0]) # 1
print(my_list[1]) # a
print(my_list[2]) # 3
print(my_list[3]) # b
print(my_list[4]) # 5
๋ฆฌ์คํธ์ n๊ฐ์ ์์๊ฐ ์์ ๋, 0๋ถํฐ n-1๋ฒ ์งธ์ ์์๋ก ์ ๊ทผ ๊ฐ๋ฅ
> ์์๋ฅผ ์ถ์ถํ์ฌ ์ฐ์ฐ์ด ๊ฐ๋ฅ
print(my_list[0] + my_list[2]) # 4
> ๋ง์ง๋ง ์์ ์ถ๋ ฅ
print(my_list[-1]) # 5
** ' - '๊ฐ์ ์ญ์์ผ๋ก ์ธ๋ฑ์ฑ
๋ฆฌ์คํธ์ ์ฌ๋ผ์ด์ฑ (slicing)
# ๋ฆฌ์คํธ๋ณ์[์์์ธ๋ฑ์ค:์ข ๋ฃ์ธ๋ฑ์ค:step]
** step์ ์๋ต๊ฐ๋ฅ
print(my_list[2:4]) # [3, 'b']
print(my_list[0:5:2]) # [1, 3, 5]
> ์์ ์ธ๋ฑ์ค๋ ์ข ๋ฃ ์ธ๋ฑ์ค๋ฅผ ์๋ต
# ๋ฆฌ์คํธ๋ณ์[์์์ธ๋ฑ์ค:]
print(my_list[:3]) # [1, 'a', 3]
# ๋ฆฌ์คํธ๋ณ์[:์ข
๋ฃ์ธ๋ฑ์ค]
print(my_list[3:]) # ['b', 5]
> ์ธ๋ฑ์ฑ์ ํ ๋ฆฌ์คํธ๋ ์ฐ์ฐ์ด ๊ฐ๋ฅ
print(my_list[:3] + my_list[3:] == my_list) # True
> ๋ฆฌ์คํธ ๋ณต์ฌํ๋ ๋ฐฉ๋ฒ
new_list = my_list[:]
print(new_list) # [1, 'a', 3, 'b', 5]
> step ํ์ฉ
print(my_list[0:5:2]) # [1, 3, 5]
print(my_list[4:2:-1]) # [5, 'b']
> ์์ ์ธ๋ฑ์ฑ๋ ๊ฐ๋ฅ
# ์ญ์์ผ๋ก ์ถ๋ ฅ
print(my_list[::-1]) # [5, 'b', 3, 'a', 1]
print(my_list[1:-1]) # ['a', 3, 'b', 5]
๋ฆฌ์คํธ์ ๊ธธ์ด (len)
# len(๋ฆฌ์คํธ)
print(len(my_list)) # 5
์ค์ฒฉ๋ ๋ฆฌ์คํธ
my_list = [1, 2, 3, ['python', 'hello', 100]]
print(len(my_list)) # 4
print(my_list[3][1][-1]) # o
print(my_list[3]) # ['python', 'hello', 100]
- ๋ฆฌ์คํธ ์์ ๋ฆฌ์คํธ๋ฅผ ์ฝ์ ํ ์ ์์
- ์ค์ฒฉ๋ ๋ฆฌ์คํธ๋ ํ๋์ ์์๋ก ์ธ์
- ์ค์ฒฉ๋ ๋ฆฌ์คํธ์ ๊ฐ๊ฐ์ ์์์ ์ ๊ทผ ๊ฐ๋ฅ
๋ฆฌ์คํธ๋ ๊ฐ๋ณ
my_list = [1, 2, 3]
my_list[0] = 100
print(my_list) # [100, 2, 3]
๋ฆฌ์คํธ์ ์ฐ์ฐ
> ๋ํ๊ธฐ
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b) # [1, 2, 3, 4, 5, 6]
> ๊ณฑํ๊ธฐ
a = [1, 2, 3]
print(a * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
๋ฆฌ์คํธ์ ์์ ๊ณผ ์ญ์
> ๋ฆฌ์คํธ ์์
a = [1, 2, 3]
a[2] = 4
print(a) # [1, 2, 4]
> ๋ฆฌ์คํธ ์ญ์
# del ๊ฐ์ฒด
a = [1, 2, 3]
del a[1]
print(a) #[1, 3]