1

I have a list:

list = ['Name0, Location0', 'Phone number0', 'Name1, Location1', 'Phone number1']

I want to split it as below

list = ['Name0', 'Location0', 'Phone number0', 'Name1', 'Location1', 'Phone number1']

I tried code below but it doesn't work.

list = ['Name0, Location0', 'Phone number0', 'Name1, Location1', 'Phone number1']
newlist =[]
newList = [line[0].split(',') for line in list]
print(newList)

How can I do it?

Amaury Liet
  • 10,196
  • 3
  • 18
  • 24
PinkPanther
  • 35
  • 1
  • 8
  • 2
    Beside the point, but `list` is a bad variable name since it [shadows](https://en.wikipedia.org/wiki/Variable_shadowing) the [builtin `list` type](https://docs.python.org/3/library/stdtypes.html#list). Use a more descriptive name, or at least something like `lst`. For an example, see [TypeError: 'list' object is not callable in python](/q/31087111/4518341). – wjandrea Jul 04 '21 at 18:34

2 Answers2

2
lines = ['Name0, Location0', 'Phone number0', 'Name1, Location1', 'Phone number1']
print([token for line in lines for token in line.split(', ')])
# Outputs ['Name0', 'Location0', 'Phone number0', 'Name1', 'Location1', 'Phone number1']

This is the same as the following nested for-loop:

lines = ['Name0, Location0', 'Phone number0', 'Name1, Location1', 'Phone number1']

result = []
for line in lines:
    for token in line.split(', '):
        result.append(token)

print(result)
enzo
  • 9,861
  • 3
  • 15
  • 38
1

If you have a small list you can try this:

lst = ['Name0, Location0', 'Phone number0', 'Name1, Location1', 'Phone number1']
s = ", "
joined = s.join(lst)
newList = joined.split(s)
print(newList)

Output:

['Name0', 'Location0', 'Phone number0', 'Name1', 'Location1', 'Phone number1']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Sayok Majumder
  • 1,012
  • 13
  • 28