

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python a += b is not always a = a + b
If two variables are of the same data types and not iterators like list and dictionary etc, then the expressions a += b is same as a =+b gives the same result. But when n iterator is involved we can not always expect the same. Below is one of such scenario.
Case of a = a +b
Here we can see when we apply the expression to a list and a string expecting they will get merged, we get back an error.
Example
x ='Hello ' z_list = [1,2,3] z_list = z_list + x print(z_list)
Output
Running the above code gives us the following result −
Traceback (most recent call last): File "C:\Users\Pradeep\AppData\Roaming\JetBrains\PyCharmCE2020.3\scratches\scratch.py", line 11, in z_list = z_list + x TypeError: can only concatenate list (not "str") to list
Case of a += b
But when we apply the expression a += b we see that the sting implicitly gets converted to series of elemnst to become a part of the list.
Example
z_list = [1,2,3] x ='Hello' z_list += x print(z_list)
Output
Running the above code gives us the following result −
[1, 2, 3, 'H', 'e', 'l', 'l', 'o']
- Related Questions & Answers
- Plus One in Python
- Find FIRST & FOLLOW for the following Grammar.\nS → A a A | B b B\nA → b B\nB → ε
- Larger of a^b or b^a in C++
- Show that the following grammar is LR (1)\nS → A a |b A c |B c | b B a\nA → d\nB → d
- Construct a Finite Automata for the regular expression ((a+b)(a+b))*.
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B in C++
- A += B Assignment Riddle in Python
- Cplus plus vs Java vs Python?
- Find a palindromic string B such that given String A is a subsequence of B in C++
- What is the Cost plus pricing method?
- Check if a string follows a^n b^n pattern or not in Python
- Construct a PDA that accepts (a,b)* language but not contain bbbb?
- Instant plus() method in Java
- LocalDate plus() method in Java
- LocalDateTime plus() method in Java
Advertisements