Divesh Sankhla
Divesh Sankhla

Reputation: 53

Write one line code to get odd and even numbers in separate arrays

I was asked this question in a tcs codevita interview. Given an array

a = [1,2,3,4,5,6,7,8,9,10]

you have to write a one line code in Python such that you get 2 different array/lists where one will contain odd numbers and the other will contain even numbers. i.e one list

odd = [1,3,5,7,9]

and other list

even =[2,4,6,8,10]

I was not able to write this code in one line. Can anyone tell me how to solve this in one line?

Upvotes: 2

Views: 6259

Answers (5)

Sajay Sunny
Sajay Sunny

Reputation: 1

Using list comprehension:    

def evenodd(myl): 
       evenlist = [num for num in myl if num % 2 == 0] 
       oddlist = [num for num in myl if num % 2 == 1]  
       print("Even numbers:", evenlist) 
       print("Odd numbers:", oddlist) 
      
    mylist=list()
    n=int(input("Enter the size of the  List:"))
    print("Enter the numbers:")
    for i in range(int(n)):
       k=int(input(""))
       mylist.append(k)
    evenodd(mylist) 

Upvotes: 0

Smart Manoj
Smart Manoj

Reputation: 5824

Using key,to get in a single list

print(sorted(j,key=lambda x:(x%2,-a.index(x))))

Upvotes: 0

k.wahome
k.wahome

Reputation: 1062

List comprehension holds the answer. But rather than comprehend on both even and odd list construction, pop one kind (even in this case) from you original list a and put in it's list and what you have left in a will be the other kind (odd):

>>> even, odd = [a.pop(index) for index, item in enumerate(a) if item % 2 == 0], a
>>> print(even,odd)
[2, 4, 6, 8, 10] [1, 3, 5, 7, 9]

Upvotes: 1

abc
abc

Reputation: 11929

You can use two list comprehensions in one line:

odd, even = [el for el in a if el % 2==1], [el for el in a if el % 2==0]

print(odd, even)
#([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])

Upvotes: 2

blhsing
blhsing

Reputation: 106553

You can slice the list with a step of 2:

odd, even = a[::2], a[1::2]

Upvotes: 0

Related Questions