4

I am a bit do not understand the principle of the addition of lists and strings in Python.

For example, we have a list:

students = ['Ivan', 'Michael', 'Olga']

The result of the expression:

students += 'John'

will be:

['Ivan', 'Michael', 'Olga', 'J', 'o', 'h', 'n']

And in this case, string 'John' will be processed as a list and every symbol will be added to list students.

But why the processing of expression:

students = students + 'John'

occurs otherwise? In this case, we just get an error.

I always thought that expressions a += b and a = a + b are equivalent. But why here in one case the string is expanded to the list, and in the other case this does not happen and we get an error?

mxsin
  • 43
  • 5
  • 1
    In [this](https://stackoverflow.com/questions/6951792/python-a-b-not-the-same-as-a-a-b) topic you can see why. – E141 Aug 01 '18 at 05:33
  • 1
    @mxsin, you can have a look at this https://hygull.github.io/codes/python2.7/stackoverflow/Q1.html. Here I have taken your problem as input and got the desired output. – hygull Aug 01 '18 at 06:06

1 Answers1

2

This is expression a += b or a = a + b will not help you with list.

If you want to add one element to list then you can try.

students = ['Ivan', 'Michael', 'Olga']
students.append('John')

If you want to join to list. Then you can do.

students = ['Ivan', 'Michael', 'Olga']
student = ['John']
students = students + student

Or

 students.extend(student) #This list concatenation method is bit faster.

If you want to dig deeper. You can refer to this article here

Hayat
  • 1,539
  • 4
  • 18
  • 32