-1

I have tried to find an explanation but couldn't, so my apologies if this is a silly question.

Having data x:

 x = [(1, {'gender': 'male'}),
      (2, {'gender': 'female'}),
      (3, {'gender': 'male'}),
      (4, {'gender': 'female'}),
      (5, {'gender': 'male'})]
      ...

A plausible solution for counting the occurrences of each gender would be:

from collections import Counter
Counter([d['gender'] for n, d in x)])

Returning:

Counter({'female':2, 'male':3})

Now I am trying to understand how "d['gender'] for n, d " works within "Counter([d['gender'] for n, d in x)]". What exactly is "n" in this case?

Many thanks for any pointers.

nick88
  • 118
  • 1
  • 8
  • ... if you have a basic question, why do you choose to ask StackOverflow instead of read tutorials? Research please. – user202729 Feb 10 '18 at 09:20
  • Not to mention that there are billions (not that much, but anyway) questions regarding list comprehension on SO. [For example this](https://stackoverflow.com/questions/20639180/explanation-of-how-list-comprehension-works). – user202729 Feb 10 '18 at 09:21
  • Thanks @user202729 I simply couldn't find a clear explanation for this dictionary setting, specifically what the n is in this case. – nick88 Feb 10 '18 at 09:28
  • Short answer: `n` is an variable. – user202729 Feb 10 '18 at 09:30
  • 1
    @liliscent Thanks, just a small tip: don't waste everyone's time commenting that someone doesn't understand something, without trying to help. – nick88 Feb 10 '18 at 09:35

1 Answers1

1

x is a list, so for <whatever> in x iterates through x and assigns each element to <whatever>.

The elements of x are tuples, so you can use tuple assignment to assign each item in the tuple to a different variable. for n, d in x means that n is assigned the first item in the tuple, and d is assigned the second item.

So the first iteration does

n, d = (1, {'gender': 'male'})

This sets n = 1 and d = {'gender': 'male'}.

the next iteration does

n, d = (2, {'gender': 'female'})

This sets n = 2 and d = {'gender': 'female'}. And so on through the entire list.

Finally, the list comprehension returns a list of d['gender'], which is the gender element from the dictionaries.

n is not used, it was just needed as a placeholder so that d could be assigned to the second item in the tuples. It could also have been written as:

[el[1]['gender'] for el in x]
Barmar
  • 741,623
  • 53
  • 500
  • 612