0

Sorry for this question, but I do not understand why the difference between the following results when adding an element to the list as a list itself to other list:

list_a=[]
list_b=['HELLO','WORLD']
for word in list_b:
    list_a.append([word])
print("Append to dist_list single word: ", list_a)
Output: Append to list_a:  [['HELLO'], ['WORLD']]
list_a=[]
list_b=['HELLO','WORLD']
for word in list_b:
    list_a.append(list(word))
print("Append to list_a: ", list_a)
output: Append to list_a:  [['H', 'E', 'L', 'L', 'O'], ['W', 'O', 'R', 'L', 'D']]
John Barton
  • 1,581
  • 4
  • 25
  • 51
  • 3
    There are no spaces in this result. The difference is that `list(word)` and `[word]` do not mean the same thing. – kaya3 Dec 05 '19 at 17:46
  • 1
    `list()` accepts iterator, in the case of `list('HELLO')` you will get list of separate characters. In the case of `['HELLO']` you will get list containing one string. – Andrej Kesely Dec 05 '19 at 17:46
  • Yes. Why are you doing this? Why not just `list_a.append(word)`? – Daniel Roseman Dec 05 '19 at 17:46
  • might you be looking for `extend`? – user1558604 Dec 05 '19 at 17:47
  • Sorry, I stated the title wrongly, each letter becomes an element in the list instead of the whole word would become an element. I am doing this because I have a process after that takes a list of lists. Usually, the result would be `[['Hello','world'],['Hola','mundo']]`, but sometimes I will get just `[['Hello','World']]` like in the example. I am adding to another list to fulfill requirements of the following process. – John Barton Dec 05 '19 at 17:52

1 Answers1

1

When you perform list() to a string, the string gets turned into a list that's separated for each individual value. For example:

a = 'string'
b = list(a) 
b = ['s','t','r','i','n','g']

Therefore the difference comes because in the first case you are appending two items (both being strings) and in the second one, you are appending the string previously turned into a list with the logic explained above, hence you've appended a list for each string. This is the differnece in the results you are getting. First case add two strings, second case add two lists.

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53