For example I have two arrays a array1
and array2
array1 = ['A', 'B', 'C', 'D', 'E', 'F',]
array2 = ['G', 'H', 'I',]`
Now I want the output as
array1 = ['A', 'B', 'C', 'D', 'E', 'G', 'H', 'I',]
How can I do this in python
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
>>> array1 = ['A', 'B', 'C', 'D', 'E', 'F']
>>> array2 = ['G', 'H', 'I']
>>> array1 = array1[:-1] + array2
>>> array1
['A', 'B', 'C', 'D', 'E', 'G', 'H', 'I']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With