Search code examples
pythonstringlistinttuples

How to change datatypes in tuples?


I'm working with a list of int's and floats, and trying to change the second parameter to string.

What I have is something like this:

array = [(12.0, 23),(9.0, 24)]

What I want is:

array = [(12.0, '23'),(9.0, '24')]

I tried using a simple for, as shown below:

for i in range(len(array)):
  array[i][1] == str(array[i][1]) 

Could anyone explain me why this does not work, and if so, an easier way to do this? Thank you very much!


Solution

  • Tuples are immutable so you can't just change them. You need to make new ones. Probably easiest with a list comprehension:

    array = [(12.0, 23),(9.0, 24)]
    
    array = [(a, str(b)) for a,b in array]
    # [(12.0, '23'), (9.0, '24')]
    

    If you need to alter the list in place, you can, but you still need new tuples:

    array = [(12.0, 23),(9.0, 24)]
    
    for i, (a,b) in enumerate(array):
        array[i] = (a, str(b))
    
    array
    # (12.0, '23'), (9.0, '24')]