Need help for an exercise (python 3)

Hi Everyone.

I need a little bit of help with an exercise I am doing at the moment.
I would like to know how to , for every integer inferior to 10 ,create a couple looking like this :
[i, [a, b, c, ….]] where [a, b, c, …] corresponds to the positions of i in the following list :
L = [3, 2, 3, 1, 2, 0, 9, 9, 9, 2, 3]
And for practical reasons, I want the result to look like this :
[[0, [5]], [1, [3]], [2, [1, 4, 9]], [3,[0, 2, 10]], [4, ], [5, ], [6, ], [7, ], [8, ], [9, [6, 7, 8]]]
The problem is that I have no idea about how to do this. Can somebody help me please ?

First of all, this is the not right place to ask for this type of question. There are several forums and of course StackOverflow that are more suitable.
Having said that, I couldn’t resist offering a solution, with two list comprehensions.

res = [[i, [j for j, v in enumerate(L) if v == i]] for i in range(10)]

Sorry Ruud, I disagree that “this is the not right place to ask for this
type of question”. It’s a question about Python, by and for users of
Python. If it is not appropriate, what sort of question would be
appropriate? (That’s not a rhetorical question.)

Of course you are correct that there are other forums which may be
better or more appropriate for a beginner, such as the tutor mailing
list or Reddit’s learnpython subreddit:

Teddy, when you have no idea how to solve a programming problem, often a
good start is to work through the exercise with pen and paper, writing
down exactly what steps you took as if you were writing instructions
for a child, or a recipe. Then translate each step into Python code.

1 Like