Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I replace value in a nested list?

Tags:

python

How do I replace James's salary from 1000 to 1500 and print James's data?

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]

for (name,appt,salary) in data:
    if name == 'James':
        salary = 1500
        print(linked_data[1]) 

Here's my current output:

['James', 'Cleaner', 1000]

Expected output:

['James', 'Cleaner', 1500]
like image 507
James Boer Avatar asked Sep 22 '26 01:09

James Boer


2 Answers

You need to find the index at which it occurs. Use enumerate.

for idx, (name,appt,salary) in enumerate(data):
    if name == 'James':
        # salary is at index 2 in the inner list
        data[idx][2] = 1500
        print(f"{name},{appt},{salary}")
like image 151
jhuang Avatar answered Sep 24 '26 17:09

jhuang


If you know the index then you can do:

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]


data[1][2] = 1500

print(data[1])

output:

['James', 'Cleaner', 1500]
like image 39
Sociopath Avatar answered Sep 24 '26 16:09

Sociopath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!