1

I am having trouble understanding this bit of code, specifically its syntax.

a_list = [1,2,3,4,5,6]  
pi = lambda s: {s:a for s, a in enumerate(a_list)}[s]

I understand the lambda functions but what is [s] doing here?

  • 2
    It's accessing a value from the dictionary that was just built by key. – jonrsharpe Dec 10 '21 at 13:25
  • 2
    This is just badly-written code - it's using the name `s` for two entirely different purposes here, and it's completely pointless to turn the entire list into a dictionary just to pick a single item from that dictionary. `lambda s: a_list[s]` would do exactly the same thing, much faster. – jasonharper Dec 10 '21 at 14:20
  • 1
    Sidenote: [avoid named lambdas](/q/38381556/4518341), use a `def` instead. – wjandrea Dec 16 '21 at 18:41
  • What do *you* think the `[s]` does? If you try picking apart the code, does it become obvious? I'm not really sure why you're confused, though the code is confusing. BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Dec 16 '21 at 18:49

1 Answers1

0

The [s] is a key to retrieve a value in the dict built in the lambda.

The s is 2 different vars with the same name, so maybe this way is more readable and it does exactly the same thing:

pi = lambda s: {key: val for key, val in enumerate(a_list)}[s]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
miorey
  • 828
  • 8
  • 19
  • 1
    It's still really bad code. Don't try to polish a turd, you know? Building the dict is pointless when you can simply do `a_list[s]`. The other thing is that [named lambdas should be avoided](/q/38381556/4518341); use a `def` instead. – wjandrea Dec 16 '21 at 18:44
  • The `[s]` is a key to retrieve a value in the dict build in the lambda. The question was about the purpose of the code not to un-ugly it. – miorey Dec 16 '21 at 20:53
  • 1
    I mean you said "more readable and it does exactly the same thing", but it'd be even more readable to scrap the dict nonsense entirely and do `a_list[s]`, which also does exactly the same thing. IMO, answers shouldn't promote bad code, so if including bad code, at least mention that it's bad and why. – wjandrea Dec 16 '21 at 20:59