This answer got me close https://gis.stackexchange.com/a/286780/204059, but I only get the last value of my list for all object fields.

Example: My list = [REL_1, REL_2, REL_3]. My layer has three objects. All objects get value REL_3.

How can I fix this?

#count features
feat_count = layer.featureCount()

#write name_list
name_list = []
for i in range(feat_count):
    rel_name = ('REL_{}'.format(i)) 

# add data to 'name' field
with edit(layer):
    for feature in layer.getFeatures():
            feature.setAttribute('name', name_list[i])
            i += 1
        except IndexError:
            feature.setAttribute('name', name_list[-1])

2 Answers 2


You need to reset the i variable. Because after the first for, Python remembers the last value of i. After the first for i value is 2 and name_list[2] is REL_3.

Add i = 0 before for feature in layer.getFeatures():


Perhaps you have a reason for creating the list in a loop like you do, but as your example is written it would appear you can skip that step and shorten your code to:

with edit(layer):
    # use enumerate to iterate the features
    for i,feature in enumerate(list(layer.getFeatures())):
        feature.setAttribute('name', f'REL_{i+1}')

enter image description here

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.