Changing tuple to list then changing element in list to another from another list then change back to tuple

I have 2 tuples (I think that’s what they are):

fs = 90,30,50,180,90,90,24,90,90

dr = 8,7,6,5,4,3,2,1,0

for num in dr:

	if num == 0:

		dr[8] = fs[8]
		

		for num in fs:

			fs[8] = (fs[8])-1
	else:

		pass

print("dr =", dr)
print()
print("fs =", fs)

when iterating through dr, if it finds a ‘0’, then I need to change ‘0’ to the corresponding number index of fs, then subtract 1 from the indexed fs item. (I hope my explanation in clear enough.

This is the last stage of a larger script that works well as is
I think I could do it if they were both lists. ie. # fs = [90,30,50,180,90,90,24,90,90]
# dr = [ 8,7,6,5,4,3,2,1,0 ]

when I try to execute code as is I get the following error:

Traceback (most recent call last):
File “test.py”, line 9, in
dr[8] = fs[8]
TypeError: ‘tuple’ object does not support item assignment

not sure at this point how to achieve desired result without altering previous code.

Any help is greatly appreciated.
Thanks in advance
cogiz
python 3.6 user

The error message says it all.

Tuple object are immutable, just like string objects.

If you need a list then make a list.

fs = [90,30,50,180,90,90,24,90,90]
dr = [8,7,6,5,4,3,2,1,0]

Tuples are for the case where you do not want the contents to change.

If I correctly understand your objective then:

  • iterate over dr
  • if value 0 is found:
    • replace 0 with item at same index in fs
    • deduct 1 from item at same index in fs
  • have fs and dr with new values as tuple

One way to achieve this is to use helper function which will iterate in parallel of both tuples using zip, will make necessary changes and yield values. Then using this helper function by unpacking its results and zip to convert rows to columns and assigning result to the same names. Something like that:

fs = 90, 30, 50, 180, 90, 90, 24, 90, 90,
dr = 8, 7, 6, 5, 4, 3, 2, 1, 0,

def helper(replace, change):
    for source, target in zip(replace, change):
        if source == 0:
            source = target
            target -= 1
        yield source, target

dr, fs = zip(*helper(dr, fs))

print(*(f'{t}, {type(t)}' for t in (fs, dr)), sep='\n')

# (90, 30, 50, 180, 90, 90, 24, 90, 89), <class 'tuple'>
# (8, 7, 6, 5, 4, 3, 2, 1, 90), <class 'tuple'>

Thank you so much.
This is exactly what I was looking for and it worked like a charm.
I never would have figured that out for myself.
I just made one very minor change to suit my needs.

fs = 90, 30, 50, 180, 90, 90, 24, 90, 90,
dr = 8, 7, 6, 5, 4, 3, 2, 1, 0,

def helper(replace, change):
    for source, target in zip(replace, change):
        if source == 0:
            source = target
            target -= 1
        yield source, target

dr, fs = zip(*helper(dr, fs))

print(*(f'{t}' for t in (fs, dr)), sep='\n')

Can’t thank you enough.
Best regards,
cogiz
python 3.6 user