Reputation: 29
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]
Upvotes: 1
Views: 2558
Reputation: 54340
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]
Upvotes: 1
Reputation: 35069
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)
Upvotes: 1
Reputation: 11396
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)
Upvotes: 2