Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'update' or 'overwrite' a python list

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']

like image 750
pyLearner Avatar asked Aug 20 '14 17:08

pyLearner


People also ask

Can you overwrite a list in Python?

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.

How do you update an element in a list?

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.


1 Answers

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 
like image 72
Rahul Tripathi Avatar answered Sep 25 '22 17:09

Rahul Tripathi