-2

In Python, I have tuple, to convert tuple to list i use

tuple1 = (1,2,3,4,5)
eq_list = []
eq_list += tuple1

it works fine.But if i use :

eq_list = eq_list + tuple1

it gives TypeError can only concatenate list (not "tuple") to list why that? isn't a += b equivalent a = a + b?

  • You need to convert tuple to list before you add. eq_list = eq_list + list(tuple1). – Joe Ferndz Jan 20 '21 at 20:57
  • https://docs.python.org/3/faq/programming.html#faq-augmented-assignment-tuple-error and https://stackoverflow.com/questions/41446833/what-is-the-difference-between-i-i-1-and-i-1-in-a-for-loop – Joe Ferndz Jan 20 '21 at 20:58
  • "Isn't a += b equivalent to a = a + b?" Not necessarily. – chepner Jan 20 '21 at 21:01

1 Answers1

2

+ is implemented using list.__add__, which expects both arguments to be instance of list.

eq_list = eq_list + tuple1  # eq_list = list.__add__(eq_list, tuple1)

+= is implemented using list.__iadd__, which expects only the first argument to be an instance of list; the second argument can be any iterable object.

eq_list += tuple1  # eq_list = list.__iadd__(eq_list, tuple1)

a += b and a = a + b are only equivalent when __iadd__ isn't defined for the given type. For example, tuple.__iadd__ isn't defined, so given x = (), both x = x + () and x += () are implemented with x = x.__add__(()).

chepner
  • 497,756
  • 71
  • 530
  • 681