0

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.

8
  • Seems perfectly reasonable. Commented Oct 17, 2017 at 20:33
  • 4
    You can just do first, second = zip(*l) (granted zip will return tuples, which you could then cast into a list. Commented Oct 17, 2017 at 20:33
  • 2
    Your way seems perfectly fine, to be honest. If you know for sure you always have two characters, you can do for c1, c2 in my_list: Commented Oct 17, 2017 at 20:39
  • 2
    @Bahrom the thing I don't like about that approach is that the * splat operator actually materializes a tuple, so, if the number of arguments is large, this becomes increasingly inefficient. Commented Oct 17, 2017 at 20:40
  • 1
    @Bahrom although, on my own initial tests it seems to beat out the naive approach by a good bit, I guess there's a major advantage to pushing the iteration out of the interpreter level... Commented Oct 17, 2017 at 20:52

2 Answers 2

2

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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']

1 Comment

How is your code different from what OP posted in the question?

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.