Hacker News new | ask | show | jobs
by haypo 4183 days ago
"As an ex Perl guy (well I still use it sometimes), I find append and extend an endless source of confusion in Python. Especially as strings do the opposite of what I expect, and get treated as character arrays with extend (or was it append)."

list.extend(data) works like "for item in data: list.append(item)"

strings (str) do not behave differently than a list or a set. Try .append() on a list or a set, you get the same behaviour.

Maybe your confusion comes from the fact that strings are immutable in Python, and a list is not a string.

You may like bytearray() in Python 2 (bytearray.append raises an error if you pass a string longer than 1 character), but there is not mutable type for Unicode strings.

1 comments

Yes but I would expect my strings to behave as a scalar variable, not a list or set.

I prefer the Perl way of having one function push, and specifically referencing the list if you want it stored that way. That has caused me far less confusion in Perl than the Python way of doing things.