if I have a list of integer
x=[0, 0, 119, 101, 108, 108, 99, 111, 109]
I'd like to cut 2 elements from left
x=[119, 101, 108, 108, 99, 111, 109]
What shall I do ?
>>> x = [0, 0, 119, 101, 108, 108, 99, 111, 109]
>>> x = x[2:]
>>> x
[119, 101, 108, 108, 99, 111, 109]
This gets every element from the third item to the end of the list, and we just make x
the value of that.
Nein nein nein
Sorry, I don't think that Haidro's solution to be good because a reassignation is performed that isn't necessary.
See:
x = [0, 0, 119, 101, 108, 108, 99, 111, 109]
print id(x)
x = x[2:]
print id(x)
print
y = [0, 0, 119, 101, 108, 108, 99, 111, 109, 1003]
print id(y)
y[:2] = []
print id(y)
result
18713576
18739528
18711736
18711736
Showing an example of x = x[2:]
causing an issue:
x = [0, 0, 119, 101, 108, 108, 99, 111, 109, 1003]
print id(x),x
gen = ((i,a+100) for i,a in enumerate(x))
for u in xrange(4):
print '%d %d' % gen.next()
x = x[2:]
print 'x = x[2:]\n',id(x),x
for u in xrange(4):
print '%d %d' % gen.next()
print '--------------------------'
y = [0, 0, 119, 101, 108, 108, 99, 111, 109, 1003]
print id(y),y
gen = ((i,b+100) for i,b in enumerate(y))
for u in xrange(4):
print '%d %d' % gen.next()
y[:2] = []
print 'y[:2] = []\n',id(y),y
for u in xrange(4):
print '%d %d' % gen.next()
result
18713576 [0, 0, 119, 101, 108, 108, 99, 111, 109, 1003]
0 100
1 100
2 219
3 201
x = x[2:]
18711736 [119, 101, 108, 108, 99, 111, 109, 1003]
4 208
5 208
6 199
7 211
--------------------------
18740128 [0, 0, 119, 101, 108, 108, 99, 111, 109, 1003]
0 100
1 100
2 219
3 201
y[:2] = []
18740128 [119, 101, 108, 108, 99, 111, 109, 1003]
4 199
5 211
6 209
7 1103
In the first case ( x = x[2:] ) , x
is reassigned to another object. But the generator created before the reassignement still uses the same list object to yield elements. This may be an issue in certain codes.
But it's true that the other code could also be an issue in other cases.
What I mean is that we aren't protected from x = x[2:]
to cause an issue, in the absolute.
z[:] = z[2:]
is notably different from y[:2] = []
:
import dis
print 'y[:2] = []'
def f(z):
y[:2] = []
dis.dis(f)
print '====================='
print 'z[:] = z[2:]'
def f(z):
z[:] = z[2:]
dis.dis(f)
result
y[:2] = []
7 0 BUILD_LIST 0
3 LOAD_GLOBAL 0 (y)
6 LOAD_CONST 1 (2)
9 STORE_SLICE+2
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
=====================
z[:] = z[2:]
12 0 LOAD_FAST 0 (z)
3 LOAD_CONST 1 (2)
6 SLICE+1
7 LOAD_FAST 0 (z)
10 STORE_SLICE+0
11 LOAD_CONST 0 (None)
14 RETURN_VALUE