6

I have a simple list as below:

lst = ['11 12221/n']

I want to split the first item into a list as below:

['11', '12221']

This seems relatively simple to me but I cant get it to work. My first approach was to do:

lst[0].split() 

but when I print list no changes have occurred. I therefore tried:

newLst=[]

for x in lst:
    newList.append(x.split())

But from this I get

[['11', '12221\n']]

I think I must fundamentally be misunderstanding list comprehension, could someone explain why my code didnt work and how it should be done?

Thank you

scottt
  • 7,008
  • 27
  • 37
PaulBarr
  • 919
  • 6
  • 19
  • 33
  • 1
    It seems that you need to use "extend" instead of "append". See [here][1] [1]: http://stackoverflow.com/questions/252703/python-append-vs-extend – Avision Apr 19 '14 at 14:51

4 Answers4

5

I believe you are looking for this:

>>> lst = ['11 12221\n']
>>> # Split on spaces explicitly so that the \n is preserved
>>> lst[0].split(" ")
['11', '12221\n']
>>> # Reassign lst to the list returned by lst[0].split(" ")
>>> lst = lst[0].split(" ")
>>> lst
['11', '12221\n']
>>>
2

Use a list comprehension:

[part for entry in origlist for part in entry.split(None, 1)]

This allows for multiple strings and splits just once (so only two elements are ever created for each string).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

You can do it as:

lst = ['11 12221\n']

lst = lst[0].split()

list[0] gets you '11 12221\n' which you then split() and assign back to lst giving you:

['11', '12221\n']

You have to assign the split back to the variable

Note: You should not name your variables as ony of the python reserved words. Use perhaps lst instead.

If you only want to split at a space, do: split(' ') instead.

Demo: http://repl.it/R8w

sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

You need to assign the result of the call to std.split to something:

>>> my_list = ['11 12221\n']     # do not name a variable after a std lib type
>>> my_list = my_list[0].split()
>>> print my_list
['11', '12221']

The main issue is that the call to str.split returns a list of strings. You were just discarding the result.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480