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

Question:

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

Asked By: pyLearner

||

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
Answered By: Rahul Tripathi

What about replace the item if you know the position:

aList[0]=2014

Or if you don’t know the position loop in the list, find the item and then replace it

aList = [123, 'xyz', 'zara', 'abc']
    for i,item in enumerate(aList):
      if item==123:
        aList[i]=2014
        break
    
    print aList
Answered By: Kerby82

I think it is more pythonic:

aList.remove(123)
aList.insert(0, 2014)

more useful:

def shuffle(list, to_delete, to_shuffle, index):
    list.remove(to_delete)
    list.insert(index, to_shuffle)
    return

list = ['a', 'b']
shuffle(list, 'a', 'c', 0)
print list
>> ['c', 'b']
Answered By: Ilya Kaznacheev

I’m learning to code and I found this same problem. I believe the easier way to solve this is literaly overwriting the list like @kerby82 said:

An item in a list in Python can be set to a value using the form

x[n] = v

Where x is the name of the list, n is the index in the array and v is the value you want to set.

In your exemple:

aList = [123, 'xyz', 'zara', 'abc']
aList[0] = 2014
print aList
>>[2014, 'xyz', 'zara', 'abc']
Answered By: Gabriel_Ferreira

If you are trying to take a value from the same array and trying to update it, you can use the following code.

{  'condition': { 
                     'ts': [   '5a81625ba0ff65023c729022',
                               '5a8161ada0ff65023c728f51',
                               '5a815fb4a0ff65023c728dcd']}

If the collection is userData[‘condition’][‘ts’] and we need to

    for i,supplier in enumerate(userData['condition']['ts']): 
        supplier = ObjectId(supplier)
        userData['condition']['ts'][i] = supplier

The output will be

{'condition': {   'ts': [   ObjectId('5a81625ba0ff65023c729022'),
                            ObjectId('5a8161ada0ff65023c728f51'),
                            ObjectId('5a815fb4a0ff65023c728dcd')]}
Answered By: Haris Np

I would prefer it without enumerate and instead use “range” like this:

for item in range(0, len(alist)):
   if 123 in alist[item]:
      alist[item] = 2014

For those who are new to python it might be more readable and a little smarter to recap.

Regards P.

Answered By: innovacode
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.