so, know how this, not seem quite pythonic mee. there cleaner way of doing this?
arr = list(range(10)) print(arr) n in range(len(arr)): # perform som operation on element changes value "in place" arr[n] += 1 print(arr)
output (which how want it):
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
what said. if want operation while you're creating list can do:
arr = [u + 1 u in range(10)]
i presume you're using python 3. if you're using python 2, change range
xrange
(unless list size small), since python 2 range
function returns actual list
, xrange
returns iterator; python 3 range
function returns iterator that's similar old xrange
(but few improvements).
if arr
existing list
want modify without replacing current list
object new list
object , can do
arr[:] = [u + 1 u in arr]
here's code illustrates difference between using arr
, arr[:]
on left hand side of assignment.
arr = list(range(10)) b = arr print(id(arr), id(b)) arr = [u + 1 u in arr] print(id(arr), id(b)) print(arr, b) c = arr print(id(arr), id(c)) arr[:] = [u + 1 u in arr] print(id(arr), id(c)) print(arr, c)
output
3073636268 3073636268 3073629964 3073636268 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3073629964 3073629964 3073629964 3073629964 [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
so arr = [u + 1 u in arr]
binds name arr
new list object, arr[:] = [u + 1 u in arr]
mutates existing list object. "under hood" creates new temporary list object , copies contents old list object.
Comments
Post a Comment