0

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.

asked Dec 11, 2013 at 2:54
1
  • 1
    What are you going for here? I'm not sure I understand what you expect paths to be... Commented Dec 11, 2013 at 2:56

4 Answers 4

1

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])
answered Dec 11, 2013 at 3:09
0

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]]
answered Dec 11, 2013 at 3:16
0

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)]
answered Dec 11, 2013 at 5:54
0

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.

answered Dec 11, 2013 at 6:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.