1
myList = ['Jay', 'Phil', 'Gloria, Claire']

I want to check every element in the list and split by comma, making the two new elements stay in the same list. Output should be:

myList = ['Jay', 'Phil', 'Gloria', 'Claire'] 

I've tried this:

newList = []
myList = ['Jay', 'Phil', 'Gloria, Claire']

for element in myList:
   newList.append(element.split(','))

but I got as output a lot of sub lists and this is not what I want:

['Jay'], ['Phil'], ['Gloria', 'Claire']

How can I solve this?

1
  • 1
    How do you want to split by a delimiter that is not in your string? Commented Apr 11, 2016 at 20:02

5 Answers 5

2

Try using extend instead of append.

for element in myList:
   newList.extend(element.split(','))
Sign up to request clarification or add additional context in comments.

2 Comments

You're going to end up with an unwanted to space with "thing, that".split(',')
@idjaw I took care of that in my answer
2

I can recomend you to use list comprehension:

newList = [element for item in myList for element in item.split(',')]

Comments

1

You have one major error

First: Appending a list to a list properly requires a different approach (using += vs. append)

Then you need to use 'strip' to remove the white space in ', Claire' to get 'Claire' (not ' Claire')

newList = []
myList = ['Jay', 'Phil', 'Gloria, Claire']

for element in myList:
   newList += element.split(',')

newList = [x.strip() for x in newList]

print newList

# ['Jay', 'Phil', 'Gloria', 'Claire']

Comments

0

Your solution is good for different problem.

if:

myList = "Jay,Phil,Gloria,Claire"

it's make sense to spilt the string to list of words.

Currently you already have a list of words so you split it doesn't make sense.

Comments

0

List comprehension works well in these case

subList = [elem.split(',') for elem in mylist]
newList = [l for elem in subList for l in elem]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.