Lewis909 Lewis909 - 23 days ago 5
Python Question

Python - How do you replace the values of strings stored in a list with the string values from another list?

I have search stack overflow and googled a solution to this problem unfortunately I haven't been able to find a solution.

I would like to replace the values of strings stored in a list with the string values from another list.

For example I have two lists:

list_a = ['file_x', 'file_x', 'file_x', 'file_x']
list_b = ['1', '2', '3', '4']


I want the result to return:

list_c =['file_1', 'file_2', 'file_3', 'file_4']


I am new to python and I am struggling to do this, i have tried using a for loop and str.replace() but I do not know how to match up the key values for each array and replace the 'x' each element of list_a with the string value from the elements of list_b.

Any help with this would be greatly appreciated.

Answer

Use zip to couple corresponding as and bs.

>>> list(zip(list_a, list_b))
[('file_x', '1'), ('file_x', '2'), ('file_x', '3'), ('file_x', '4')]

We can use this zip object easily in a for loop, unpacking the pairs into separate variables a and b, then doing the a.replace('x', b) and appending the resulting value to our result list:

>>> list_c = []
>>> for a, b in zip(list_a, list_b):
...    list_c.append(a.replace('x', b))
...
>>> list_c
['file_1', 'file_2', 'file_3', 'file_4']

This can also be written as a short list comprehension:

>>> [a.replace('x', b) for a, b in zip(list_a, list_b)]
['file_1', 'file_2', 'file_3', 'file_4']

And as Moinuddin points out, using a format string here is a better option if you defined the contents of list_a