like extremely new, so please bear with me.
Im trying to increment each element of a nested list by 1
a straight forward list works fine:
a = [1,2,3,4,5,6,7,8]
for i in range(len(a)):
a[i] += 1
but why doesn't it work with:
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
what am i missing?
-
You need another for loop to loop inside list.Frank– Frank05/08/2020 03:49:33Commented May 8, 2020 at 3:49
5 Answers 5
Let's unroll the loop so we can inspect:
a = [1, 2, 3, 4, 5, 6, 7, 8]
i = 0
assert a[i] == 1 # the zeroeth element of a
a[i] += 1 # increment 1, making it 2
assert a[i] == 2
i = 1
# ... etc, repeat
contrast with
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
i = 0
assert a[i] == [1, 2] # the zeroeth element of a is now the list [1, 2]!
a[i] += 1 # TypeError! What's the logical equivalent of adding 1 to a list? There isn't one
It won't work as you have another list inside list a or nested list. Therefore, you need nested loop: Following program would help:
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
for i in range(len(a)):
for j in range(len(a[i])):
a[i][j] += 1
Hope it Helps!!!
In the first iteration your a[i] += 1
would effectively be a[0] = [1, 2] + 1
. That doesn't exactly make sense. You need to have a second, inner loop.
Use nested for loops:
for i in range(len(a)):
for ii in range(len(a[i])):
a[i][ii] += 1
Because you have nested list then you have to iterate that nested one again
Here a cool way to check if there list inside with recursion
a = [1,[2, 4],3,[4, 5],5,6,7,8]
def increment_a_list(some_list):
for i in range(len(some_list)):
if type(some_list[i]) is list: # if the element is a list then execute the function again with that element
increment_a_list(some_list[i])
else:
some_list[i] += 1 # +1 to that element if it not a list
return some_list
print(increment_a_list(a))
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
Each item in the list is again a list. You need to traverse and incerement each of it individually. So, nested for loop
can solve your problem.
A more generic solution - Recursion
### Using recursion - The level of nesting doesn't matter
def incrementor(arr):
for i in range(len(arr)):
if type(arr[i]) is list:
incrementor(arr[i])
else:
arr[i] = arr[i] + 1
a = [[1, 2], [3, 4], [5, 6], [7, 8],9,10,11,12,[13,[14,15,16]],[[17,18],[19,[20,21]]]]
incrementor(a)
print(a)
Output
[[2, 3], [4, 5], [6, 7], [8, 9], 10, 11, 12, 13, [14, [15, 16, 17]], [[18, 19], [20, [21, 22]]]]