0

Say I have a list of strings like so:

list = ["Jan 1", "John Smith", "Jan 2", "Bobby Johnson"]

How can I split them into two separate lists like this? My teacher mentioned something about indexing but didn't do a very good job of explaining it

li1 = ["Jan 1", "John Smith"]
li2 = ["Jan 2", "Bobby Johnson"]
1

4 Answers 4

5

Well, use list slicing:

li1 = my_list[:2]
li2 = my_list[2:]

BTW, don't use the name list for a variable because you are shadowing the built-in list type.

Sign up to request clarification or add additional context in comments.

Comments

1

If your list is longer than just two entries you could do this:

zip(list[0::2],list[1::2])

Output:

[('Jan 1', 'John Smith'), ('Jan 2', 'Bobby Johnson')]

Comments

0

One of ways to do make it work with lists of arbitrary length in a clean and simple manner:

all_lists = (list[x:x+2] for x in range(0, len(list), 2))

And then you can access new lists by:

li1 = all_lists[0]
li2 = all_lists[1]

Or just iterate through them:

for new_list in all_lists:
    print(new_list)

As all_lists is a generator (in both Python 2.X and 3.X) it will also work on large chunks of data.

Comments

0

If the length of the list isn't always going to be the same, or known from the start you can do this:

original_list = [YOUR ORIGINAL LIST]

A = [:len(original_list)/2]
B = [len(original_list)/2:]

A will be the first half and B will be the second half.

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.