1

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]
lvc
  • 34,233
  • 10
  • 73
  • 98
  • What exactly are you asking? Is the final bit a desired output, or a current output? Also what is the logic behind it? – Slater Victoroff Dec 07 '13 at 01:43
  • Ah sorry part of my post looks like it was eaten, the second block is desired out put. It supposed to take values[0] and add the user input and replace values[1] with it. something akin to values[1] = values [0] + user. If I didn't have to append the data it would be easy. – user3029955 Dec 07 '13 at 01:50

3 Answers3

2

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)
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42
1

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)
lvc
  • 34,233
  • 10
  • 73
  • 98
  • Thank you a ton, I actually tried that a bit earlier and kept getting an error message I couldn't decipher. Apparently my syntax was wrong. The overwrite I mean, which was my original goal. – user3029955 Dec 07 '13 at 01:55
  • @user3029955 please consider [accepting](http://stackoverflow.com/help/accepted-answer) my answer if you found it helpful. – lvc Dec 07 '13 at 05:38
1

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]
CT Zhu
  • 52,648
  • 17
  • 120
  • 133