Reputation: 1093
Recently came into a weird problem. I'm trying to change an item in a tuple I've converted to a list.
But what I had,
paths = [(1,2),(2,3),(2,0)]
plist = []
for pathlist in paths:
for n in range(0, len(pathlist)):
if pathlist[n] == 2:
plist = list(pathlist)
plist[n] = 4
pathlist = tuple(plist)
print(pathlist)
print(paths)
Didn't actually change the value in the list paths
, i.e. it stayed the same as originally, even though I could tell from print(pathlist)
that it had been modified correctly. And I can't remove it and append it because that would offset the for loop. Thanks for your help, guys.
Upvotes: 0
Views: 456
Reputation: 231375
While initially pathlist
points to an element of path
, that link is lost when it is reassigned within the loop.
for pathlist in paths:
...
pathlist = 'new value'
Try this simpler case with a list of integers. alist
is not changed.
alist = [1,2,3]
for x in alist:
x = x*2
But if the elements are lists, they can be changed without loosing that link to alist
.
alist = [[1],[2],[3]]
for x in alist:
x[0] = x[0]*2
Unfortunately, for these purposes, your tuples are more like integers than lists. You either have to use indexing to modify alist[i]
, or rebuild the list as in the list comprehension answer.
Upvotes: 0
Reputation: 2137
you should append the pathlist to some list in each turn...try this one
paths = [(1,2),(2,3),(2,0)]
flist = []
for pathlist in paths:
for n in range(0, len(pathlist)):
if pathlist[n] == 2:
plist = list(pathlist)
plist[n] = 4
pathlist = tuple(plist)
flist.append(pathlist)
print(flist)
the output will be
[(1, 4), (4, 3), (4, 0)]
Upvotes: 0
Reputation: 28252
You are only changing the list-copy you modified. You're not directly modifying paths
.
Do it like this:
>>> for i, pl in enumerate(paths):
for j, n in enumerate(pl):
if n==2:
pl = list(pl)
pl[j] = 4
paths[i] = pl
>>> paths
[[1, 4], [4, 3], [4, 0]]
Upvotes: 0
Reputation: 1748
the pathlist var is a new instance, it will not affect the paths list members.
try this:
for i in range(len(paths)):
pathlist = paths[i]
for n in range(0, len(pathlist)):
if pathlist[n] == 2:
plist = list(pathlist)
plist[n] = 4
paths[i] = tuple(plist)
print(paths[i])
Upvotes: 1