'I have a double nested list. I would like to remove the second element inside of the nested list. i.e. [[[x,1],[x,2],[x,3]],[[x,1],[x,2],[x,3]]]
for x in y:
[z.pop(0) for z in x]
IndexError: pop index out of range.
The function seems to keep looping after it has gone through all the values of x. I would like to move on the next value of x after it has done it has completed its work. I understand that the error is occurring due to the changing of my data shape, but how do I avoid this?
Solution 1:[1]
First solution:
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
for lst in nested_list:
for j in lst:
j.pop(1)
print(nested_list)
The above solution will give you the following output:
[[[11], [20], [300]], [[100], [202], [303]]]
Second Solution
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
result = []
for lst in nested_list:
for j in lst:
result.append(j[0])
print(result)
del nested_list
The above solution will give you the following output:
[11, 20, 300, 100, 202, 303]
If you are familiar with python then you can also go with the following:
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
def return_first(lst):
return [j[0] for i in lst for j in i]
print(return_first(nested_list))
del nested_list
The above solution will give you the following output:
[11, 20, 300, 100, 202, 303]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aps08 |
