리스트에 적용되는 메서드

(1) sort()
(2) append() /insert()
(3) pop() /remove()
(4) count()

(1) sort()

sort() : sorts the list ascending by default.
🍟 리스트안의 요소를 오름차순으로 나열한다. reverse=True를 입력하면 내림차순으로 나열할 수 있다.

기본형

sort(reverse=True/False | key=함수)

Example

lst = ['j', 'u', 'r', 'i']
lst.sort()
print(lst)
#['i', 'j', 'r', 'u']
  • 리스트안에 str요소와 int요소가 같이 있을 땐 사용할 수 없다.

🍩 내장함수 sorted
returns a sorted list of the specified iterable object.

기본형

sorted(iterable | reverse=True) : 내림차순 정렬

(2) append() /insert()

append() : Adds an element at the end of the list
insert() : Adds an element at the specified position
🍟리스트의 끝/ 지정된 위치에 요소를 추가할 수 있다.

기본형

append(element)
insert(position, element)

Example

lst = ['j', 'u', 'r', 'i']
lst.append('!') #맨 끝에 추가 
lst.insert(2, '!') #인덱스2번에 추가

(3) pop() /remove()

pop() : removes the element at the specified position.
remove() : removes the first occurrence of the element with the specified value.
🍟 지정된 위치에 있는 / 지정된 값을 갖는 첫번째 요소를 제거한다.

기본형

pop(position)
remove(value)

Example

lst = ['i', 'j', 'u', 'r', 'i']
lst.pop(0) #['j', 'u', 'r', 'i']
lst.remove('i') #['j', 'u', 'r', 'i']
print(lst)

(4) count()

count() : returns the number of elements with the specified value.
🍟 리스트 안에서 지정된 값을 갖는 element의 갯수를 반환한다.

Example

points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
#2

후기 : 굉장히 많이 사용되는 메서드들이니까 헷갈리지 않게. 특히 기능은 비슷하지만 세부사항이 다른 경우가 많으니까 잘 구별해서 사용할 것.

profile
Make my day !

0개의 댓글

Powered by GraphCDN, the GraphQL CDN