aList = [123, 'xyz', 'zara', 'abc'] aList.append(2014) print aList
which produces o/p [123, 'xyz', 'zara', 'abc', 2014]
What should be done to overwrite/update this list. I want the o/p to be
[2014, 'xyz', 'zara', 'abc']
You can replace items in a list using a Python for loop. To do so, we need to the Python enumerate() function. This function returns two lists: the index numbers in a list and the values in a list. We iterate over these two lists with a single for loop.
To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set() method to update the replace the old element with new element. Find index of existing element using indexOf() method. Use set(index, object) to update new element.
You may try this
alist[0] = 2014
but if you are not sure about the position of 123 then you may try like this:
for idx, item in enumerate(alist): if 123 in item: alist[idx] = 2014
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