EgzEst
EgzEst

Reputation: 361

Can't update value of list element in python

Can someone explain why the below mentioned behavior happens, in debug mode, why cannot I update a list element value:

enter image description here

I don't get, what I'm doing wrong? My code:

 if request.method == 'GET':
        coordinates = mongo_harassments_utils.get_geolocated({})
        count =  coordinates.count()
        for i in range(coordinates.count()):
            first = coordinates[i]["story"]
            coordinates[i]["story"] = "Test"
            second = coordinates[i]["story"]

Upvotes: 0

Views: 95

Answers (2)

Sergei Lebedev
Sergei Lebedev

Reputation: 2679

In your example coordinates is not a list, but a pymongo.cursor.Cursor. You need to explicitly coerce it to a list for the code to work:

if request.method == 'GET':
    coordinates = list(mongo_harassments_utils.get_geolocated({}))
    count = len(coordinates)
    for i in range(len(coordinates)):
        first = coordinates[i]["story"]
        coordinates[i]["story"] = "Test"
        second = coordinates[i]["story"]    

Also, explicit indexing is often considered an anti-pattern in Python. For your case enumerate is perfectly applicable

for i, coordinate in enumerate(coordinates):
    first = coordinate["story"]
    coordinate["story"] = "Test"
    second = coordinate["story"]  

Note that with enumerate you no longer need to make coordinates a list.

Upvotes: 1

pdepmcp
pdepmcp

Reputation: 136

I suspect that the issue is that it's not a list. Not all iterables are lists, and in your particular situation "coordinates" looks like a mongodb cursor.

Upvotes: 0

Related Questions