Home > database >  Modify tuples inside a list
Modify tuples inside a list

Time:08-02

I'm trying to make a bunch of tuples show only one decimal using a for loop.

Van = (500.3736434, 43.834434)
Vbn = (300.2321313, 64)
Vcn = (250.43513241, 12)

listap = [Van, Vbn, Vcn]

for i in range(0,len(listap)):
    listap[i] = tuple([float("{0:.1f}".format(n)) for n in listap[i]])

The desired result is only displayed when I print a specific index in the list, like print(listap[0])for example. Anyway I can get the reduced tuples without using the list? for example, doing

print(Van)
>>> (500.4, 43.8)

CodePudding user response:

Python tuples are immutable - you cannot modify them in place. What you could do is, instead to convert into the desired format and rename the converted variables to the same name -

Van, Vbn, Vcn = [tuple([float("{0:.1f}".format(n)) for n in el]) for el in listap]
print(Van)
# (500.4, 43.8)

CodePudding user response:

You have to create a new tuple.

new_list = []
for old_tuple in listap:
    new_tuple = tuple([round(i, 1) for i in old_tuple])
    new_list.append(new_tuple)
print(new_list)
# [(500.4, 43.8), (300.2, 64), (250.4, 12)]

But, if you just want to print them as a list, you can do:

for old_tuple in listap:
    print([round(i, 1) for i in old_tuple])

which outputs

[500.4, 43.8]
[300.2, 64]
[250.4, 12]
  • Related