플그래밍/파이써언

[파이썬] list 관련 method 알아보기

훗티v 2023. 8. 12. 11:52
728x90
반응형

파이썬 리스트와 관련된 메서드와 예제입니다



1. append(item)

리스트의 맨 끝에 항목을 추가합니다.

fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits)  # 출력: ['apple', 'banana', 'cherry', 'orange']



2. extend(iterable)

리스트와 반복 가능한 객체(iterable)를 연결합니다.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # 출력: [1, 2, 3, 4, 5, 6]



3. insert(index, item)

지정한 인덱스 위치에 항목을 삽입합니다.

colors = ['red', 'green', 'blue']
colors.insert(1, 'yellow')
print(colors)  # 출력: ['red', 'yellow', 'green', 'blue']



4. remove(item)

리스트에서 지정한 항목의 첫 번째 발생 사례를 제거합니다.

animals = ['cat', 'dog', 'rabbit', 'dog']
animals.remove('dog')
print(animals)  # 출력: ['cat', 'rabbit', 'dog']



5. pop(index=-1)

지정한 인덱스(기본값은 마지막 항목)에서 항목을 제거하고 반환합니다.

stack = [10, 20, 30, 40]
popped_item = stack.pop()
print(popped_item)  # 출력: 40
print(stack)        # 출력: [10, 20, 30]



6. index(item[, start[, end]])

지정한 항목의 첫 번째 발생 인덱스를 반환합니다.

colors = ['red', 'green', 'blue', 'green']
index = colors.index('green')
print(index)  # 출력: 1



7. count(item)

리스트에서 지정한 항목의 발생 횟수를 반환합니다.

numbers = [1, 2, 3, 4, 3, 5]
count = numbers.count(3)
print(count)  # 출력: 2



8. sort(key=None, reverse=False)

리스트의 요소를 오름차순(기본값) 또는 내림차순으로 정렬합니다.

numbers = [3, 6, 2, 8, 5]
numbers.sort()
print(numbers)  # 출력: [2, 3, 5, 6, 8]



9. reverse()

리스트의 요소를 역순으로 배치합니다.

colors = ['red', 'green', 'blue', 'yellow']
colors.reverse()
print(colors)  # 출력: ['yellow', 'blue', 'green', 'red']



10. clear()

리스트의 모든 요소를 제거합니다.

fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)  # 출력: []



11. del(list[index])

지정한 인덱스 위치의 항목을 제거합니다.

colors = ['red', 'green', 'blue', 'yellow']
del(colors[1])
print(colors)  # 출력: ['red', 'blue', 'yellow']
반응형