1

How to optimize the below code. Can anyone help me::

a=[1,2,3,4]
b=[]
c=[]
for i in a:
    if i%2==0:
        b.append(i)
    else:
        c.append(i)
cs95
  • 379,657
  • 97
  • 704
  • 746

1 Answers1

2

You're creating two lists, so instead, why not delete from one of them?

even = [1, 2, 3, 4]
odd = []
for i in reversed(range(len(even))):
    if even[i] % 2 != 0:
        odd.insert(0, even.pop(i))

pop removes from the first, and insert(0, ...) will add it to the start (in its right position). Additionally, you iterate over b in reverse as is common with the reverse-delete idiom.

You will end up with b and c as before. Complexity wise, however, it's still the same.


If order isn't important, change odd.insert(0, even.pop(i)) to odd.append(even.pop(i)) which is slightly easier to read.

cs95
  • 379,657
  • 97
  • 704
  • 746