달나라 노트

Python Basic : list pop (list에서 특정 index 위치의 요소 제거) 본문

Python/Python Basic

Python Basic : list pop (list에서 특정 index 위치의 요소 제거)

CosmosProject 2022. 10. 10. 23:51
728x90
반응형

 

 

 

list의 pop method는 특정 index에 위치한 요소를 제거하고 제거된 요소를 return해줍니다.

그리고 원본 list에도 명시된 index 위치에 있는 요소가 제거된 채로 변형됩니다.

 

 

Syntax

list.pop(index)

 

pop method는 제거할 요소의 index를 parameter로 받습니다.

 

 

 

 

list_test = [1, 2, 3, 4, 5]

removed_element = list_test.pop(1)

print(removed_element)
print(list_test)



-- Result
2
[1, 3, 4, 5]

 

list_test.pop(1) -> 이것의 의미는 list_test에서 index = 1 위치에 있는 요소를 제거한 후 제거된 그 요소를 return합니다.

 

그래서 결과를 보면 removed_element는 pop method의 결과로서 제거된 요소인 2가 할당되며

원본 list인 list_test는 index = 1 위치에 있었던 2가 제거된 채로 존재하게됩니다.

 

 

 

 

 

 

 

list_test = [1, 2, 3, 4, 5]

removed_element = list_test.pop()

print(removed_element)
print(list_test)



-- Result
5
[1, 2, 3, 4]

 

pop method에 parameter를 전달하지 않으면 가장 오른쪽에 있는 가장 마지막 요소를 제거합니다.

 

 

 

 

 

list_test = [1, 2, 3, 4, 5]

removed_element = list_test.pop(-2)

print(removed_element)
print(list_test)



-- Result
4
[1, 2, 3, 5]

 

pop method에서도 일반적인 list의 indexing을 따릅니다.

따라서 위 예시처럼 index로서 음수를 전달하여 오른쪽에서 부터의 indexing으로 pop method를 사용할 수 있습니다.

 

 

 

 

 

 

728x90
반응형
Comments