Click here to Skip to main content
15,301,841 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a nested list called inputs. Let's assume that it is like so
inputs = [[1,0,1],[0,0,1]]

Now I added 3 empty lists (row_1,row_2,row_3) they should be appended by the respectful index in a list in the nested list. For further explanation:
#They should be like this
row_1 = [1,0]
row_2 = [0,0]
row_3 = [1,1]


What I have tried:

Python
row_1 = []
row_2 = []
row_3 = []
for lists in inputs:
    for index in lists:
        row_1.append(inputs[index - 1][0])
        row_2.append(inputs[index - 1][1])
        row_3.append(inputs[index - 1][2])


Which resulted in:
row_1 = [1,0,1,1,1,1]
row_2 = [0,0,0,0,0,0]
row_3 = [1,1,1,1,1,1]


I suspect that the problem is in the for loop. Can it be solved with a while loop?
Posted
Updated 27-Nov-21 9:05am

1 solution

I would try something like
Python
row_1 = []
row_2 = []
row_3 = []
for lists in inputs:
    for index in lists:
        row_1.append(inputs[index - 1][0])
        row_2.append(inputs[index - 1][1])
        row_3.append(inputs[index - 1][2])
    row_1.append(lists[0])
    row_2.append(lists[1])
    row_3.append(lists[2])


Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

27.3. pdb — The Python Debugger — Python 3.6.1 documentation[^]
Debugging in Python | Python Conquers The Universe[^]
pdb – Interactive Debugger - Python Module of the Week[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
   
Comments
Eyad Mohamed 27-Nov-21 15:15pm
   
Thank you so much! I will consider using a debugger. Once again thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900