How to split an element in a list? - Python 3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to split an element in a list? - Python 3

If I had a list that looked like: list1 = [‘A dog, a cat’, ‘a mouse, a rabbit’] How would I iterate through the list so I could split it using .split(‘,’) I would want the outcome to look like: list1 = [‘a dog’, ‘a cat’, ‘a mouse’, ‘a rabbit’] So that they are seperate elements rather than a joint string if that makes sense?

29th May 2020, 12:22 PM
Luna
9 Answers
+ 9
list1 = ["A dog, a cat", "a mouse, a rabbit"] b=[] for i in list1: b+=i.split(",") print(b)
29th May 2020, 12:55 PM
Abhay
Abhay - avatar
+ 8
I would prefer the version from HonFu, but i was to late. So for the reason of showing different approaches, here is a version using a comprehension: out1 = [] [out1.extend(i.split(', ')) for i in list1] print(out1)
29th May 2020, 3:33 PM
Lothar
Lothar - avatar
+ 3
You could make a new list, iterate through the list and append all items to the new list with the help of the split method.
29th May 2020, 12:32 PM
Seb TheS
Seb TheS - avatar
+ 3
Following Seb TheS's algorithm, list1 = ['A dog, a cat', 'a mouse, a rabbit', 'a horse'] separator, list2 = ', ', [] for e in list1: if separator in e: list2.extend(e.split(separator)) else: list2.append(e) print(list2)
29th May 2020, 12:55 PM
Ipang
+ 3
list2 = ', '.join(list1).split(', ')
29th May 2020, 1:03 PM
HonFu
HonFu - avatar
+ 3
$¢𝐎₹𝔭!𝐨𝓝 , just run this piece of code: list1 = ['A dog, a cat', 'a mouse, a rabbit'] list1 = ', '.join(list1).split(', ') print(list1) It's exactly what Luna wanted to get as a result.
29th May 2020, 4:37 PM
HonFu
HonFu - avatar
+ 2
Personally: join it into a single string, and then split it into a list. list1 = ['A dog, a cat', 'a mouse, a rabbit'] list1 = ', '.join(list1).split(', ') print(list1) # ['A dog', 'a cat', 'a mouse', 'a rabbit'] Edit: I realised that didn't quite answer your question in the way you asked it, but I'll leave it up to demonstrate another possible way of doing it.
29th May 2020, 12:59 PM
Russ
Russ - avatar
0
HonFu I think your answer was not relevant to the question.
29th May 2020, 4:28 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
By simply using split function or you can google it
31st May 2020, 9:01 AM
Aman Yadav
Aman Yadav - avatar