-4

Suppose you wanted to sort a collection of strings by the number of distinct letters in each string:

strings = ['foo', 'card', 'bar', 'aaaa', 'abab']

Here we could pass a lambda function to the list’s sort method:

strings.sort(key=lambda x: len(set(list(x))))
strings
['aaaa', 'foo', 'abab', 'bar', 'card']
DavidG
  • 24,279
  • 14
  • 89
  • 82
Kevin Phu
  • 1
  • 1
  • the `list(x)` is superflous in this keydefinition: `key=lambda x: len(set(list(x)))` strings are already iterables and the set() can be applied to any iterable, not only lsits. – Patrick Artner Nov 01 '18 at 15:02

2 Answers2

0

It is counting the unique letters for each word.

len(set(list(x))) #creating a set.

A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed).

Sort function takes this as criteria for sorting. It will evaluate and sort the elements depending on this lambda expression.

Petar Velev
  • 2,305
  • 12
  • 24
0

sort calls the given key function on each element of the list, and uses the return value of the function when comparing two elements. In this case, the elements of your list are sorted according to how many unique characters each element contains. For example, aaaa comes first because the key function evaluates to 1, and it is the only element containing only a single unique character.

To answer the question in the title, x is an element of the list strings.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I got it, Thank you! so key=lambda x evaluates how many unique letters in each element of the string list. – Kevin Phu Nov 01 '18 at 14:33