0

Here is the 1st code.

lst=11*[[]]

print(lst)
word="Mia"
value=0
for i in word:
    value+=ord(i)
n=value%11 #Loaction number
lst[4]+=[word]
print(lst)

This output will be this [['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia'], ['Mia']]

The 2nd one.

lst=11*[[]]

print(lst)
word="Mia"
value=0
for i in word:
    value+=ord(i)
n=value%11 #Loaction number
lst[4]=lst[4]+[word]
print(lst)

This will produce this result. [[], [], [], [], ['Mia'], [], [], [], [], [], []]

What's the difference between lst[4]=lst[4]+[word] and lst[4]+=[word]?

I originally assume the abbreviation of lst[4]=lst[4]+[word] is lst[4]+=[word].

But they're apparently not.

kile
  • 141
  • 1
  • 7
  • You have value += ord(i) but you never defined ord. I think you have made a typo in the code that is causing this – The Grand J Nov 16 '20 at 04:18
  • 1
    @TheGrandJ, The ord() function in Python accepts a string of length 1 as an argument and returns the unicode code point representation of the passed argument. – Joe Ferndz Nov 16 '20 at 04:20
  • My mistake. Thanks for correcting me – The Grand J Nov 16 '20 at 04:21
  • @kile, are you sure the first set of code gives you empty list and not ['mia'] 11 times? – Joe Ferndz Nov 16 '20 at 04:24
  • Does this answer your question? https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists#:~:text=It%20takes%20all%20the%20elements,create%20a%20new%20list%20object. – Joe Ferndz Nov 16 '20 at 04:33
  • 1
    Does this answer your question? [Why does += behave unexpectedly on lists?](https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists) – Joe Ferndz Nov 16 '20 at 04:36
  • @JoeFerndz Sorry for the problematic result. I'll correct it now – kile Nov 16 '20 at 04:41
  • the += operator on list works as extend. Thats why you get `'mia'` added to every element. See the link I posted. It should help. – Joe Ferndz Nov 16 '20 at 04:43

0 Answers0