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


i wanted create names a1, b2, c3 , d4

batches = zip('abcd', range(1, 5))  in batches:   batch = i[0] + str(i[1])   print(batch) 

this produces output expected:

a1 b2 c3 d4 

however, if initialize list batch_list empty , add each batch it, follows:

batch_list = []  batches = zip('abcd', range(1, 5))  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'] 

by using += operator appending each item in string batch_list. 1 way avoid breaking string wrap in list.

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

output

['a1', 'b2', 'c3', 'd4']  

btw, it's better use list.append , list.extend methods use +=. although code using += shorter, using methods makes code little more readable, there other benefits well, ability mutate global lists, although may argue shouldn't doing anyway. ;)


but there better ways write this.

you can use list comprehension, , let .format method combine letter number, way there's no need explicitly call str constructor.

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

another option use enumerate, rather zipping range. enumerate function allows supply starting number, rather using default starting number of zero.

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

this efficient way, unless have python 3.6, in case can use f-string formatting:

batch_list = [f'{v}{i}' i, v in enumerate('abcd', 1)] 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -