Reputation: 35
Can someone help me with below. I have a list like below.
list = ['INDIA,CHINA,JAPAN','FRANCE,IRELAND,ENGLAND']
I am trying to convert above list into below.
newlist = ['INDIA','CHINA','JAPAN','FRANCE','IRELAND','ENGLAND']
I have tried split()
which is not working.
newlist = list.split(',')
Thanks much for your help.
Upvotes: 0
Views: 78
Reputation: 26
You can use a List Comprehension to achieve this easily
list = ['INDIA,CHINA,JAPAN','FRANCE,IRELAND,ENGLAND']
print([word for string in list for word in string.split(',')])
Output
['INDIA', 'CHINA', 'JAPAN', 'FRANCE', 'IRELAND', 'ENGLAND']
Upvotes: 0
Reputation: 111
list = ['INDIA,CHINA,JAPAN','FRANCE,IRELAND,ENGLAND']
newlist = []
for item in list:
newlist.extend(item.split(','))
print(newlist)
This will produce:
['INDIA', 'CHINA', 'JAPAN', 'FRANCE', 'IRELAND', 'ENGLAND']
Upvotes: 0
Reputation: 15872
It is never a good idea to name your variables same as python keywords or builtin methods. Try naming it something different. For this problem you do not need any explicit for loops, there are suitable list methods to do this for you:
list_ = ['INDIA,CHINA,JAPAN','FRANCE,IRELAND,ENGLAND']
newlist = ','.join(list_).split(',')
#Output:
['INDIA', 'CHINA', 'JAPAN', 'FRANCE', 'IRELAND', 'ENGLAND']
Upvotes: 2
Reputation: 22776
You should use split
with the strings in the list, not the list:
L = ['INDIA,CHINA,JAPAN', 'FRANCE,IRELAND,ENGLAND']
new_L = [x for s in L for x in s.split(',')]
print(new_L)
Output:
['INDIA', 'CHINA', 'JAPAN', 'FRANCE', 'IRELAND', 'ENGLAND']
Upvotes: 2
Reputation: 1555
try this :
list = ['INDIA,CHINA,JAPAN','FRANCE,IRELAND,ENGLAND']
result = []
for i in list :
s = i.split(",")
for j in s :
result.append(j)
print(result)
output :
['INDIA', 'CHINA', 'JAPAN', 'FRANCE', 'IRELAND', 'ENGLAND']
Upvotes: 0
Reputation: 6920
Try this :
list_ = ['INDIA,CHINA,JAPAN','FRANCE,IRELAND,ENGLAND']
newlist = []
for i in list_:
newlist += i.split(',')
Output :
['INDIA', 'CHINA', 'JAPAN', 'FRANCE', 'IRELAND', 'ENGLAND']
Upvotes: 1