-1

I have a 2 elements list which I want to extend with the elements of another one. playing around in Jupyter I found this strange behaviour that I can not understand.

# this is my first list
columnslist=['app','SUM']
['app','SUM']

# it is going to be extended with the values A and B

columnslist.extend(['A','B'])
['app','SUM','A','B']

# It is possible to make a list out of a string in this way
print(list('AB'))
['A','B']

# I realise that list('AB')= ['A','B']
This works:
columnslist.extend(list('AB'))

# but the following does not work:
mytext='this is a text to be split'
columnslist.extend(mytext.split())

why is that so? thanks

JFerro
  • 3,203
  • 7
  • 35
  • 88
  • 2
    Where have you seen `list[...]` and why do you feel this is more correct than the `list(...)` syntax you used just one line above? – cs95 Dec 23 '18 at 16:30
  • thanks. that was a typo – JFerro Dec 23 '18 at 16:32
  • `list['AB']` is not the correct syntax IMHO. `list(['AB'])` – cph_sto Dec 23 '18 at 16:34
  • You fixed the "typo" with something more incorrect. – cs95 Dec 23 '18 at 16:35
  • typos corrected. What I see is that list gets a string into () and gives a list which elements are the characters of the string. @cph: in list(['AB']) you are passing to list a list, since ['AB'] is a list with one element. list(['AB']) gives ['AB'] and not 'A', 'B'. – JFerro Dec 23 '18 at 16:47
  • What exactly "doesn't work"? What are you expecting instead? – chepner Dec 23 '18 at 16:52
  • `list('AB')` gets an iterable as an argument; the iterable contains two 1-character strings `'A'` and `'B'`. `list(['AB'])` *also* gets an iterable as an argument; that iterable contains a single 2-character string `'AB'`. `['AB']` has an extra layer of iteration compared to `'AB'`; it's an iterable that contains an iterable. – chepner Dec 23 '18 at 16:54
  • by mytext='this is a text to be split' columnslist.extend(mytext.split()) I would expect columnslist=['app','SUM','A','B', 'this','is','a','text','to','be','split'] – JFerro Dec 23 '18 at 18:54

2 Answers2

-1

First thing it's bad practice to use keywords as variable. Second thing it can't make use of extend function since it's a dictionary object.

Edit: I hope that i am guessing it right, you want to extract alphabet in a string with whitespaces? then you can try following code

>>>my_list= ["A","B"]
>>>test_str = "This is a text"
>>>my_list.extend(list("".join(test_str.split())))
['A','B','T', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 'x', 't']
Gaurav
  • 533
  • 5
  • 20
-1

The text is separated by space, you can use .split here. .split converts a string in a list.

columnslist.extend(mytext.split(' '))
YOLO
  • 20,181
  • 5
  • 20
  • 40