Syed Naqi Syed Naqi -4 years ago 102
Python Question

how to add elements to a list in python

I have a function the encrypt and decrypt a message I want my function to display the answer as such: ['DHBK', 'VZVP'] but right now this is how it is displaying the result: ['D', 'H', 'B', 'K', 'V', 'Z', 'V', 'P'] how can I change my program so it doesn't do that. Right now this is how I'm adding to the list

for message in messages:
message = process_message(deck, message, encrypt_decrypt)
new_messages += message
return new_messages

Answer Source

The + (and by extension +=) operators joins sequences. A string is a sequence, leading to this:

>>> l = [1, 2, 3]
>>> s = 'abc'
>>> l += s
>>> l
[1, 2, 3, 'a', 'b', 'c']

You likely want the append method instead:

>>> l = [1, 2, 3]
>>> s = 'abc'
>>> l.append(s)
>>> l
[1, 2, 3, 'abc']

PS. If instead you actually wanted the original result, using the 'extend' method of the string would have been clearer. If instead you were going to join some strings you can avoid confusion caused by using + for joining by using string formatting instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download