0

I looked at the following question. I wanted to do the same in Python.

List a=[ 1,2,3 none, none] list b=[4,5,3] Output=[1,4,2,5,3,3]

z = [ x for x in a if x != None ] + b

This does not work. I want the z to be [1,4,2,5,3,3]

Community
  • 1
  • 1
paddu
  • 693
  • 1
  • 7
  • 19
  • 2
    What are the constraints on the positions of the `None`s? And how do they influence the output? e.g. what if the first element of `a` was `None`? What output would you want then? – mgilson Dec 15 '15 at 21:12
  • @ajcr - Agreed it is kind of duplicate but the other question did not have the None condition – paddu Dec 15 '15 at 21:16
  • I agree it's a fine line - happy to reopen if you feel that those answers aren't directly applicable to your case here (someone else had suggested that duplicate first). – Alex Riley Dec 15 '15 at 21:18
  • @ajcr -- after cleaning up the duplicate issue, I agree that this is a duplicate. – Mike Lyons Dec 15 '15 at 21:28
  • Thanks guys. I totally agree and it looks like it is a duplicate. – paddu Dec 15 '15 at 23:25

3 Answers3

4
from itertools import chain
list(chain.from_iterable(zip([1, 2, 3, None, None], [4, 5, 6])))

zip(a, b) as mentioned above will create a list of tuples, and chain.from_iterable will flatten the list, discarding Nones

Mike Lyons
  • 22,575
  • 2
  • 16
  • 19
2

It looks like you want to chain the lists after ziping them together and removing None ...

from itertools import chain, izip_longest
with_none = chain.from_iterable(izip_longest(a, b, fillvalue=None)]
without_none = [x for x in with_none if x is not None]
mgilson
  • 300,191
  • 65
  • 633
  • 696
1

Use zip(a, b) followed by flattening of list:

>>> [item for subtuple in zip(a, b) for item in subtuple]
[1, 4, 2, 5, 3, 3]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • all these people doing some weird itertools stuff, quite unnecessary. +1 for plain simplicity – R Nar Dec 15 '15 at 21:12
  • 1
    I personally find itertools to be much more simple than nested list-comprehensions -- But I suppose it's what you're used to... – mgilson Dec 15 '15 at 21:13
  • @mgilson Yup :) Still not used to `itertools` in Python :( Never found the use till now in 6 months since I started using Python in production :) – Rohit Jain Dec 15 '15 at 21:14
  • @RohitJain -- That's a good question . . . – mgilson Dec 16 '15 at 03:57