ERJAN
ERJAN

Reputation: 24516

why are strings added as chars in this example python?

l = []
d1 = 'string1'
d2 = 'string2'
ds = [d1, d2]
ds
['string1', 'string2']
for d in ds:
    l+=d
    
l
['s', 't', 'r', 'i', 'n', 'g', '1', 's', 't', 'r', 'i', 'n', 'g', '2']

Since d1 and d2 are separate strings, why are still added as chars? we add them in the loop as strings, separate entities, I expect list l to be

l = ['string1', 'string2']

Upvotes: 0

Views: 64

Answers (1)

coding_gecko972
coding_gecko972

Reputation: 82

Try using .append() instead of +=:

for d in ds:
    l.append(d)

+= extends your strings, instead of just appending them to the end of your list.

Upvotes: 2

Related Questions