Skip to content Skip to sidebar Skip to footer

How To Split A List Item In Python

Suppose, I have a list like the following: names= ['my name xyz','your name is abc','her name is cfg zyx'] I want to split them like following: my_array[0]= ['my','name','xyz'] my

Solution 1:

You could define my_array using a list comprehension:

my_array = [phrase.split() for phrase in names]

which is equivalent to

my_array = list()
for phrase in names:
    my_array.append(phrase.split())

Demo:

In [21]: names= ["my name xyz","your name is abc","her name is cfg zyx"]

In [22]: my_array = [phrase.split() for phrase in names]

In [23]: my_array
Out[23]: 
[['my', 'name', 'xyz'],
 ['your', 'name', 'is', 'abc'],
 ['her', 'name', 'is', 'cfg', 'zyx']]

In [24]: my_array[0][1]
Out[24]: 'name'

One problem with defining my_array this way:

while i < len(names_abc):
    my_array= names_abc[i].split()

is that my_array is assigned to a new list each time through the while-loop. So my_array does not become a list of lists. Instead, after the while-loop, it only retains its last value.

Instead of printing my_array[0], try print(my_array) itself. It might become more clear why you're getting the result you were getting.

Solution 2:

You could split() every element in your list, which by default will split on spaces.

>>> names= ["my name xyz","your name is abc","her name is cfg zyx"]
>>> [i.split() for i in names]
[['my', 'name', 'xyz'], ['your', 'name', 'is', 'abc'], ['her', 'name', 'is', 'cfg', 'zyx']]

Solution 3:

I would create a new list and fill it with lists containing temporaray strings build from the characters of your starting list.

The temporary string is ended by the space, when a string is complete it is added to a temoprary list (list_tmp).

After all items are processed as strings and added to the temporary list, we append that list the final list:

a=["my name xyz","your name is abc","her name is cfg zyx"]

l=[]

for i in enumerate(a):
        tmp_str = ''
        list_tmp=[]
        for j in i[1]:
                if" " in j:
                        list_tmp.append(tmp_str)
                        tmp_str=''else:
                        tmp_str+=j
        else:
                list_tmp.append(tmp_str)

        l.append(list_tmp)

print l
print l[0][1]

Post a Comment for "How To Split A List Item In Python"