0

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"]
3
  • @idjaw I did that only for reasons that in that picture you can see the values on debug mode Commented Mar 11, 2016 at 13:03
  • @Lafexlos as u can see in the picture, u see that even after I assign a string value "Test" in coordinates[i]['story'] the value still remain the same Commented Mar 11, 2016 at 13:06
  • Yeah, I saw that later and that's why I removed my comment but seems like I was slow. Commented Mar 11, 2016 at 13:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.