79489665

Date: 2025-03-06 14:27:37
Score: 3
Natty:
Report link

When new to python and programming, I struggled with a means to edit a specific record in a list. List comprehensions will EXTRACT a record but it does not return an .index() in my_list. To edit the record in place I needed to know the .index() of the actual record in the list and then substitute values and this, to me, was the real value of the method.

I would create a unique list using enumerate():

unique_ids = [[x[0], x[1][3]] for x in enumerate(my_list)]

Without getting into details about the structure of my_list, x[0] in the above example was the index() of the record whereas the 2nd element was the unique ID of the record.

for example, suppose the record I wanted to edit had unique ID "24672". It was a simple matter to locate the record in unique_ids

wanted = [x for x in unique_ids if x[1] == "24672"][0] wanted (245, "24672")

Thus I knew the index at the moment was 245 so I could edit as follows:

my_list[245][6] = "Nick"

This would change the first name field in the my_list record with index 245.

my_list[245][8] = "Fraser"

This would change the last name field in the my_list record with index 245.

I could make as many changes as I wanted and then write the changes to disk once satisfied.

I found this workable.

If anyone knows a faster means, I would love to know it.

Reasons:
  • Blacklisted phrase (0.5): I need
  • Blacklisted phrase (1): anyone knows
  • Long answer (-1):
  • No code block (0.5):
  • Unregistered user (0.5):
  • Starts with a question (0.5): When
  • Low reputation (1):
Posted by: Nick Fraser