Replacing items in a two dimensional list in python

2.4k views Asked by At

I am trying to append the second item in my two dimensional. I have tried a few dozen different ways and can't seem to get it to append.

def main():
    values = [[10,0], [13, 0], [36, 0], [74,0], [22,0]]
    user = int(input('Enter a whole number'))
    for i in range(len(values)):
        print(values[i])

(current out put)

10, 0

13, 0

36, 0

74, 0

22, 0

(were the second part it is values[0] + user input)

[10, 12]

[13, 15]

[36, 38]

[74, 76]

[22, 24]
3

There are 3 answers

1
Guy Gavriely On

with list comprehension

user = 2
[[x[0], sum(x)+user] for x in values]
>>> [[10, 12], [13, 15], [36, 38], [74, 76], [22, 24]]

or using map:

map(lambda x: [x[0], sum(x)+user], values)
2
lvc On

First, you can nearly always avoid iterating over range(len(iterable)) - in this case, your loop can be written as the much nicer:

for value in values:
    print(value)

for exactly the same functionality.

I'm not sure from your description exactly how you want the code to behave, but it seems like you want something like this - each line of output will have the first item of the corresponding value, and then that added to the user input; ie, ignoring the second item of the existing input entirely:

for value in values:
    total = value[0] + user
    print((value[0], total))

or if you want it to overwrite the second item of each value for later use in your program:

values = [[10,0], [13, 0], [36, 0], [74,0], [22,0]]
for value in values:
    value[1] = value[0] + user
    print(value)
0
CT Zhu On

Shouldn't it be just like this?

>>> def f():
    values = [[10,0], [13, 0], [36, 0], [74,0], [22,0]]
    user = int(input('Enter a whole number'))
    for i in range(len(values)):
        values[i][1]=values[i][0]+user
            print(values[i])


>>> f()
Enter a whole number2
[10, 12]
[13, 15]
[36, 38]
[74, 76]
[22, 24]