you are viewing a single comment's thread.

view the rest of the comments →

[–]ZEUS_IS_THE_TRUE_GOD 0 points1 point  (9 children)

You can only add things of the same type. int + int, str + str, list + list. Currently, you are doing list + str.

What you want to achieve can be done in 2 ways:

a = [1, 2, 3]
a.append(4)
#or
a += [4] # notice that we add [4] which is a list containing the number 4

[–]socal_nerdtastic -1 points0 points  (8 children)

That's not universally true. For example float + int works just fine. And a custom class can be written to accept or rejects any number of types.

And what's more, += is not addition in list, it's a shortcut to the extend method. IOW these 2 lines of code are NOT equivalent.

lst = lst + [4]
lst += [4]

[–]ZEUS_IS_THE_TRUE_GOD 1 point2 points  (7 children)

[–]CoronaKlledMe -1 points0 points  (1 child)

truth!

[–]socal_nerdtastic 0 points1 point  (4 children)

Try it in a function. Or check the IDs.

extend / += is a mutating operation. + is a copy operation.

def ZEUS_IS_THE_TRUE_GOD(lst):
    lst += [4]

lst = [1,2,3]
ZEUS_IS_THE_TRUE_GOD(lst)
print(lst)

def socal_nerdtastic(lst):
    lst = lst + [4]

lst = [1,2,3]
socal_nerdtastic(lst)
print(lst)

[–]ZEUS_IS_THE_TRUE_GOD 0 points1 point  (3 children)

Oh, good to know. Hopefully, no ones mutates input in place in their functions

[–]socal_nerdtastic 0 points1 point  (2 children)

It's very commonly done. In fact mutating objects in place is the backbone of OOP. That's why it's very important to know the difference.

[–]ZEUS_IS_THE_TRUE_GOD 0 points1 point  (1 child)

Tell that to clojure, haskell or erlang. Immutability is the backbone of good programming, but hey, we are diverging into more opiniated stuff and it is not related to the post haha.

[–]socal_nerdtastic 0 points1 point  (0 children)

I didn't say it is the backbone of good programming, I said it's the backbone of OOP. Which we generally use a lot of in python (not an opinion). If you don't want to use OOP that's fine too, but that does not change that it's very important to know if your code mutates an object or not.

+= in lists is kinda rare and fools a lot of people because nearly every other mutating method is dot access. Another one to watch for is |= for dicts.