0

I have a list:

my=['A', 'kk','lo','A','o','t','A','t']

I want to make a nested list whenever I there is an 'A' in the list

Example output:

my_nest=[['A', 'kk','lo'],['A','o','t'],['A','t']]

I tried to do that but not sure how make it work:

  my_nest=[]
  my_nest_sub=[]
for i in my:
    if i!='A':
        my_nest_sub.append(i)
    elif i=='A':
        my_nest.append(my_nest_sub)
    my_nest_sub=[]
Cory
  • 5,645
  • 3
  • 28
  • 30
  • 1
    Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. – Prune Aug 13 '21 at 21:40
  • 2
    Most of all, this is the time to learn some basic debugging. Your code has indentation problems; it fails to run at all. With the indentation at the start fixed, there are multiple errors within the code. You haven't traced what is happening within your code; if nothing else, use some strategically placed `print` statements to verify that things work the way you expect. We expect you to ask for help with *one* problem, not dump an untested code block with a generic "fix my code". Those first steps are your responsibility. – Prune Aug 13 '21 at 21:44
  • Take a look at https://www.learnbyexample.org/python-list-insert-method/. Also, run a step debugger, like pdb, which allows you to run the code one line at a time. https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues – Cory Aug 14 '21 at 13:58

1 Answers1

1

Your loop logic is off, to fix it try something like this:

my_nest=[]
my_nest_sub=[]
for i in my:
    if i=='A':
        if my_nest_sub:
            my_nest.append(my_nest_sub)
        my_nest_sub=[]
    my_nest_sub.append(i)
my_nest.append(my_nest_sub)

For example, if you want 'A' to be in your my_nest sublists, why do you never append i when it is 'A'?

As Prune said, next time try to insert some print functions to better understand what your code actually does.

Marius Wallraff
  • 391
  • 1
  • 5
  • 11