BingbongKim
BingbongKim

Reputation: 579

Python - how to split a string list into two?

There is a list like:

list = ['AB', 'CD', 'EF', 'GH']

I would like to split this list like:

first =  ['A', 'C', 'E', 'G']
second = ['B', 'D', 'F', 'H']

Now I did like this :

for element in list:
    first.append(element[0])
    second.append(element[1])

Is it a good way? Actually, the length of list over 600,000.

Upvotes: 0

Views: 135

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

list = ['AB', 'CD', 'EF', 'GH']

first, second = zip(*list)
print(first)
print(second)

Output:

('A', 'C', 'E', 'G')
('B', 'D', 'F', 'H')

Upvotes: 2

Chetan_Vasudevan
Chetan_Vasudevan

Reputation: 2414

Looping through the list and appending to a pair of empty list can be done something like the below shown example.

 list = ['AB', 'CD', 'EF', 'GH']
 first=[]
 second=[]
 for f in list:
    first.append(f[0])
    second.append(f[1])
 print(first)
 print(second)

The output would be like

['A', 'C', 'E', 'G']

['B', 'D', 'F', 'H']

Upvotes: 1

Related Questions