-2

i'd like to know: what's the difference between these two:

return "-".join([c.upper() + c.lower() * i for i,c in enumerate(txt)])
return "-".join([c.upper() + c.lower() * i for c,i in enumerate(txt)])

I just changed the 'i' with the 'c' and the whole code doesn't work. Is there a simple explanation?

1 Answers1

3

Yes. enumerate() yields pairs of (index, item) from a given iterable.

For a string "hello", it would return (formatted as a list)

[
  (0, 'h'),
  (1, 'e'),
  (2, 'l'),
  (3, 'l'),
  (4, 'o'),
]

For the sake of simplicity, let's look at the first item only, (0, 'h').

If you use i, c to unpack this, i's value will be 0, and c's value will be 'h', and c.lower() etc. makes sense, as does multiplication with the number i.

If you use c, i to unpack this, c's value will be 0, and i's value will be 'h', and c.lower() no longer exists since c is a number and i is a string.

AKX
  • 152,115
  • 15
  • 115
  • 172