["python","list"]
How can I partition (split up, divide) a list based on a condition?

I have some code like: good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] The goal is to split up the contents of mylist into two other lists, based on whether or not they meet a condition. How can I do this more elegantly? Can I avoid doing two separate iterations over mylist? Can I improve performance by doing so?
good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] is there a more elegant way to do this? That code is perfectly readable, and extremely clear! # files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ] IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png') images = [f for f in files if f[2].lower() in IMAGE_TYPES] anims = [f for f in files if f[2].lower() not in IMAGE_TYPES] Again, this is fine! There might be slight performance improvements using sets, but it's a trivial difference, and I find the list comprehension far easier to read, and you don't have to worry about the order being messed up, duplicates being removed as so on. In fact, I may go another step "backward", and just use a simple for loop: images, anims = [], [] for f in files: if f.lower() in IMAGE_TYPES: images.append(f) else: anims.append(f) The a list-comprehension or using set() is fine until you need to add some other check or another bit of logic - say you want to remove all 0-byte jpeg's, you just add something like.. if f[1] == 0: continue