In Python, why are zipped elements 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 leads to the expected result:

A1
B2
C3
D4

However, if I initialize the batch_list as empty and add each batch to it, follow these steps:

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']
+4
source share
4 answers

Using the operator +=, you add each element to a string to yours batch_list. Thus, one way to avoid line breaking is to wrap it in a list.

batch_list = []
for i in zip('ABCD', range(1,5)):
    batch_list += [i[0] + str(i[1])]
print(batch_list)

Output

['A1', 'B2', 'C3', 'D4'] 

, list.append list.extend, +=. += , , , , , .;)


.

, .format , str.

batch_list = ['{}{}'.format(*u) for u in zip('ABCD', range(1, 5))]

- enumerate, zping range. enumerate , .

batch_list = ['{}{}'.format(v, i) for i, v in enumerate('ABCD', 1)]

, , , Python 3.6, f- :

batch_list = [f'{v}{i}' for i, v in enumerate('ABCD', 1)]
+2

.

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

:

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

:

batch_list.append(i[0] + str(i[1]))
+3

, , . Python :

>>> l = []
>>> l += 'ab'
>>> l
['a', 'b']

- += , , . += - list.__iadd__:

>>> l = []
>>> l.__iadd__('abc')
['a', 'b', 'c']

list.__iadd__ , list.extended:

>>> l = []
>>> l.extend('ab')
>>> l
['a', 'b']

, list.append :

batch_list.append(i[0] + str(i[1]))
+3
>>> from itertools import count
>>> batch_list = []
>>> for i, v in zip('ABCD', count(1)): # count(1) -> start counter at 1
...     batch = '{}{}'.format(i, v)
...     batch_list.append(batch)
... 
>>> batch_list
['A1', 'B2', 'C3', 'D4']
0

Source: https://habr.com/ru/post/1684060/


All Articles