python에서 pop() vs pop(0)

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
test = [0, 0, 0, 1, 2, 3, 4, 5, 6]  
test1 = [0, 0, 0, 1, 2, 3, 4, 5, 6]  

for _dummy in test:
    if(_dummy == 0):
        test.pop()
for _dummy in test1:
    if(_dummy == 0):
        test1.pop(0)

print(test)
print(test1)

결과는 아래와 같다

1
2
[0, 0, 0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]

그 이유는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
start of loop
[0,0,0,1,2,3,4,5,6]  
 ^   <-- position of index  
  
delete first element (since current element = 0)  
[0,0,1,2,3,4,5,6]  
 ^  
  
next iteration  
[0,0,1,2,3,4,5,6]  
   ^  
  
delete first element (since current element = 0)  
[0,1,2,3,4,5,6]  
   ^  

Categories:

Updated: