Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why zipped elements get separated, when added to a list?

I wanted to create names like A1, B2, C3 and D4

batches = zip('ABCD', range(1, 5))

for i in batches:
  batch = i[0] + str(i[1])
  print(batch)

This produces the output as expected:

A1
B2
C3
D4

However, if I initialize a list batch_list as empty and add each batch to it, as follows:

batch_list = []

batches = zip('ABCD', range(1, 5))

for i in batches:
  batch_list += i[0] + str(i[1])

print(batch_list)

The output goes as:

['A', '1', 'B', '2', 'C', '3', 'D', '4']

Why not?

['A1', 'B2', 'C3', 'D4']
like image 261
Seshadri R Avatar asked Jan 29 '23 18:01

Seshadri R


1 Answers

Because it considers your string as an array.

>>> arr = []
>>> arr += 'str'
>>> arr
['s', 't', 'r']

Try this:

batch_list += [i[0] + str(i[1])]

Or this:

batch_list.append(i[0] + str(i[1]))
like image 86
Danil Speransky Avatar answered Feb 01 '23 06:02

Danil Speransky