파이썬/파이썬(python) 초급

[4-3 파이썬] 리스트함수, append(), extend(), insert(), remove(), pop(), clear(), count(), sort(), reverse(), copy()

Olivia-BlackCherry 2022. 8. 11. 10:25

리스트 관련 함수

이번 시간에는 리스트의 값을 변경할 수 있는 함수에 대해 알아보겠다.

 

list.append(x)

Add an item to the end of the list. Equivalent to a[len(a):] = [x].

리스트의 끝에 값을 첨가하는 것.

 

list.extend(iterable)

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

리스트의 끝에 리스트를 첨가하는 것

 

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

특정한 장소에 특정한 값을 넣는 것.

i는 순서 index를 의미하고

x는 값을 의미한다.

 

list.remove(x)

Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

특정한 x값을 지우는 것

 

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

방금 전 이야기한 remove()함수와 지운다는 기능은 같다. 

하지만 pop()함수는 특이한 기능이 있어 주의 깊게 봐야 하는 부분이 있다.

 

먼저 popcorn이 튀겨지는 모습을 생각해보자.

pop(펑하는 소리를 내며 터뜨려진다)+corn(옥수수) 

 

옥수수가 펑하는 소리를 내며 터뜨려지는 것처럼

pop은 먼저 해당 인덱스 값이 출력된다. 

그리고 나서 그 리스트에서 지워진다. 

 

list.clear()

Remove all items from the list. Equivalent to del a[:].

리스트 안의 아이템을 모두 삭제한다.

 

 

list.count(x)

Return the number of times x appears in the list.

그 리스트에 있는 x가 몇 개 있는지 숫자를 센다.

 

list.sort(*, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

리스트의 값을 순서대로 정렬한다.

 

list.reverse()

Reverse the elements of the list in place.

리스트의 값을 역순으로 정렬한다.

 

list.copy()

Return a shallow copy of the list. Equivalent to a[:].

리스트를 똑같이 복사한다.