2

I'm still a beginner at learning Python. I want to ask something about loops. I found a written code like this:

user_ids = [u for u, c in user_ids_count.most_common(n)]
movie_ids = [m for m, c in movie_ids_count.most_common(m)]

how to read this code? I know that user_ids is the object and user_ids_count.most_common() is the function/method (please correct me if I'm wrong), but I have no idea what the logic sense of u for u, c and what does that mean because I can't find any loops example that's written like this.

Happy Ahmad
  • 1,072
  • 2
  • 14
  • 33
  • This is a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) – Mureinik Sep 05 '22 at 16:24
  • The generator(s) of a comprehension share the same keywords (`for` and `in`) with a `for` loop, but they are distinct syntactic constructs. – chepner Sep 05 '22 at 16:32
  • 2
    I am out of close votes for today, but the canonical duplicate is [here](https://stackoverflow.com/questions/34835951/). – Karl Knechtel Sep 05 '22 at 16:50
  • Thank you for the references. I just know about a list comprehension because I didn't learn it in my basic course and didn't stumble on it while searching on the internet. – Safiella Citra Sep 06 '22 at 06:10

1 Answers1

2

You are right. The user_ids_count.most_common() is the function/method. But the user_ids is a variable that stores the address for a list that you are creating.

The user_ids_count.most_common() method returns a list of tuples which means each element in that list consists of two values. With u for u, c in, you make an iteration on the list elements, in each iteration assign the first value in the tuple to u, and the second value in the tuple to c. Then you build a new array with u values.

Here is an example:

[u for u, c in [(1, 2), (3, 4), (5, 6)]]

will return:

[1, 3, 5]
Happy Ahmad
  • 1,072
  • 2
  • 14
  • 33