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"]
k3n3t1c
  • 33
  • 4
  • You can check [this SO question](http://stackoverflow.com/q/509211/5488275) and answers (like [this one](http://stackoverflow.com/a/509295/5488275)) to learn more about slicing in Python. – Nander Speerstra Aug 02 '16 at 13:24

4 Answers4

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.

Graham
  • 7,431
  • 18
  • 59
  • 84
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
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')]
sietschie
  • 7,425
  • 3
  • 33
  • 54
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.

Peter Nimroot
  • 545
  • 5
  • 14
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.

Harrison
  • 5,095
  • 7
  • 40
  • 60