-1

I am studying list in python and I wonder how to input lists inside a list and saw this method to input multiple list inside a list:

 from itertools import groupby
 values = [0, 1, 2, 3, 4, 5, 351, 0, 1, 2, 3, 4, 5, 6, 750, 0, 1, 2, 3, 4, 559]
 print([[0]+list(g) for k, g in groupby(values, bool) if k])
 

I tried to execute this in http://pythontutor.com/ to see the process step-by-step and I don't know what bool is checking if true or false before printing this output: [[0, 1, 2, 3, 4, 5, 351], [0, 1, 2, 3, 4, 5, 6, 750], [0, 1, 2, 3, 4, 559]]

link of the code above: Creating a list within a list in Python

1
  • your example is an additional reason why I downvote list comprehensions answers provided to beginners... Commented Nov 28, 2020 at 12:39

1 Answer 1

0

Best way to understand such problems is to dissect it.

for k,g in groupby(values,bool):
    if k:
        print(*g)
# output
1 2 3 4 5 351
1 2 3 4 5 6 750
1 2 3 4 559
for k,g in groupby(values,bool):
    if not k:
        print(*g)
# output
0
0
0

Python considers bool(0) as False. So basically, it groups all the numbers between False together and it adds them to [0] therefore you get your result. bool(any non 0) is True.

for k,g in groupby(values,bool):
    print(k)
    print(*g)

#output
False
0
True
1 2 3 4 5 351
False
0
True
1 2 3 4 5 6 750
False
0
True
1 2 3 4 559
for k,g in groupby(values,bool):
    print(k)
    if k:
        print([0]+list(g))
# output
False
True
[0, 1, 2, 3, 4, 5, 351]
False
True
[0, 1, 2, 3, 4, 5, 6, 750]
False
True
[0, 1, 2, 3, 4, 559]

Note

I might have explained myself loosely, what I meant by it groups what's between False together, is because they are True.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.