2

I need to split a list into halves such that if it has an odd length the middle element is ignored entirely, I have a function for this, but it's quite slow for what I'm trying to do.

My function (variables renamed because they make no sense out of context):

def splitList(array):
    half = len(array)/2
    if len(array)%2==0:
        return array[:half], array[half:]
    else:
        return array[:half], array[half+1:]

This function has to be called about 17 million times if my estimations are correct, so it has to be rather faster. Since I'm new to this though, if you could explain why your answer works faster, that would be perfect :)

last-minute thingy: it's for a small part of a projectEuler challenge if you were wondering, you're supposed to be able to get an answer in under a minute is why it has to be so fast.

Faceplanted
  • 61
  • 3
  • 7
  • see [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – Artjom B. Jun 08 '14 at 11:53
  • 2
    seems to me that you want http://codereview.stackexchange.com/ – Artjom B. Jun 08 '14 at 11:55
  • One of the points of project euler is that if your code isn't fast enough by a significant amount, it's probable that you can vastly improve it with a better *algorithm*, not just by optimising implementation details. That said, if you really want to be faster, you probably should use a numpy array or something. – inclement Jun 08 '14 at 11:56
  • Those functions won't work though, Artjom B, if I have a length 5 list, I'd input chunks(2,list) and it would give me three lists with the last element exactly where I don't need it. – Faceplanted Jun 08 '14 at 11:58
  • I don't think the linked answers are entirely relevant to this question though, they're asking about a list of arbitrary length to be split evenly in half. Not to split the list into same sized chunks – dangel Jun 27 '20 at 01:40

1 Answers1

2

This works and seems like a simple way:

def splitList(array):
    n = len(array)
    half = int(n/2) # py3
    return array[:half], array[n-half:]
dangel
  • 7,238
  • 7
  • 48
  • 74
Mark
  • 18,730
  • 7
  • 107
  • 130