๐ List ์ ์ธ
๊ธฐ๋ณธ ์ ์ธ
>>> my_list = []
Comprehension
>>> my_list = [item for item in temp_list]
lambda ์์ฝ์ด
>>> my_list = list(map(lambda x:x*2, temp_list))
๐ ์ฐ์ฐ
๋ํ๊ธฐ
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> list1 + list2
[1, 2, 3, 4, 5, 6]
๋ฐ๋ณต
>>> my_list = [1, 2, 3]
>>> my_list * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
- ๋ฆฌ์คํธ ๋ฐ๋ณต์ ์์๋ณต์ฌ(shallow copy) ์ด๋ฏ๋ก, ๋ฐ๋ณต ํ ๊ฐ๋ณ item์ ํน์ ์์
์ ํด์ฃผ๋ฉด ๋ฐ๋ณต๋ ๋ค๋ฅธ item์๋ ๊ฐ์ ์์
์ด ์ ์ฉ๋จ
>>> my_list = [[2, 5]] * 3
>>> my_list
[[2, 5], [2, 5], [2, 5]]
>>> my_list[0].append(7)
>>> my_list
[[2, 5, 7], [2, 5, 7], [2, 5, 7]]
๐ ์ฌ๋ผ์ด์ฑ
- list [a : b] ๋ list[a] ~ list[b-1] ๊น์ง์ ํญ๋ค์ ์ฌ๋ผ์ด์ฑํด์ ๋ฐํ, ๊ธธ์ด๋ b-a
- list[-1]์ ๋ง์ง๋ง ํญ์ด๋ฏ๋ก ์ฌ๋ผ์ด์ฑ ํ ๋ ์ด์ฉ๊ฐ๋ฅ
>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[1:3]
[2, 3]
>>> my_list[:2]
[1, 2]
>>> my_list[2:]
[3, 4, 5]
>>> my_list[1:-1]
[2, 3, 4]
๐ ์ ๋ ฌ
sort()
>>> my_list.sort()
>>> my_list.sort(reverse=True)
>>> my_list.sort(key=f)
>>> my_list.reverse()
sorted()
>>> sorted(my_list)
>>> sorted(my_list, reverse=True)
>>> sorted(my_list, key=lambda x:f(x))
๐ ๋ด๋ถ ํจ์
append()
>>> my_list = [element1]
>>> my_list.append(element2)
>>> my_list
[element1, element2]
extend()
- ๋ฆฌ์คํธ ๋ํ๊ธฐ ์ฐ์ฐ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์๋ก ํ ๋น, extend๋ ๊ทธ ์ฃผ์์ ๊ทธ๋๋ก ๋ฉ๋ชจ๋ฆฌ๋ง ํ์ฅ
>>> my_list = [1,2,3]
>>> my_list.extend([4,5,6])
>>> my_list
[1, 2, 3, 4, 5, 6]
index()
- List ๋ด๋ถ ํน์ element์ ์ธ๋ฑ์ค ๋ฐํ
>>> my_list
[element1, element2]
>>> my_list.index(element2)
1
>>> my_list.index(element3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 0 is not in list
insert()
- List ์ ํน์ index์ element ์ฝ์
>>> my_list.insert(0, element3)
>>> my_list
[element3, element1, element2]
count()
- List ์ ๋งค์นญ๋๋ element ๊ฐ์๋ฅผ ๋ฐํ
>>> my_list = [1, 5, 5, 3, 7, 0, 1, 2]
>>> my_list.count(5)
2
>>> my_list.count(13)
0
in
- List ๋ด๋ถ์ element๊ฐ ์กด์ฌํ๋์ง๋ฅผ bool๋ก ๋ฐํ
- ์๊ฐ๋ณต์ก๋๊ฐ O(n)์ด๊ธฐ ๋๋ฌธ์, ํน๋ณํ ๊ฒฝ์ฐ๊ฐ ์๋๋ผ๋ฉด dictionary ๋ set๋ฅผ ์ด์ฉํด์ ์กด์ฌ์ฌ๋ถ๋ฅผ ํ๋ณํ๋ ๊ฒ์ด ๋์
>>> 35 in [1, 35, 90, 100]
True
>>> 11 in [1, 3, 5, 10]
False
>>> 11 not in [1, 3, 5, 10]
True