0

I was trying to write the opening blanks for a hangman game. My code was:

display = []
for x in (word):
    display = display + "_"
print(display)

I understand that here, python thinks I'm trying to numerically add _ to a list object, which is not possible, but why is it that display += "_" works fine?

Nelewout
  • 6,281
  • 3
  • 29
  • 39
Sarthak
  • 11
  • 2
  • 4
    Please explain what *numerically add _ to a list* means? – Guy Jul 14 '22 at 07:06
  • 1
    What do you mean by "its full form"? Will you show two versions of the code using the two forms you are refering to? And then show how the outputis different. – Code-Apprentice Jul 14 '22 at 07:09
  • I think a part of my question got omitted for some reason. I meant to type that display = display + "_" does not seem to work, whereas display += "_" works fine, although they are supposed to mean the same thing – Sarthak Jul 14 '22 at 07:09
  • @Sarthak Feel free to [edit] your question to fix it. – Code-Apprentice Jul 14 '22 at 07:10
  • It is indeed possible in python to program the operators such that `+=` acts differently from "`+` followed by assignment". – qrsngky Jul 14 '22 at 07:11
  • 3
    [Why does += behave unexpectedly on lists?](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists) – Guy Jul 14 '22 at 07:13
  • Just finished the edit, hope my doubt comes off clearer now. Apologies for the confusion! – Sarthak Jul 14 '22 at 07:13
  • Even though `print(display+ "_" )` does not work, you can do `print(display+["_"])` – qrsngky Jul 14 '22 at 07:13
  • Please provide a [mcve] that illustrates the behavior you are asking about. This should be something we can copy and paste and run ourselves. Your current code example has an undefined variable, so I can't run it. Also be sure to include the two different behaviors so we can see how the output differs. – Code-Apprentice Jul 14 '22 at 07:13
  • 1
    I is instructive to see what happens when you do `display += "foobar"`. – Code-Apprentice Jul 14 '22 at 07:17
  • Cheers @Guy, I had stumbled upon that thread while searching for an answer to my problem but thought it was somehow irrelevant to my question, I'll go through it once more. – Sarthak Jul 14 '22 at 07:18
  • Thank you for your help @Code-Apprentice, I think my doubt has been addressed. I'll keep your pointers in mind when I inevitably return for help with some miniscule doubts. – Sarthak Jul 14 '22 at 07:18

0 Answers0