Reputation: 135
Let's say that I have three lists and want to add all elements that are integers to a list named int_list
:
test1 = [1, 2, 3, "b", 6]
test2 = [1, "foo", "bar", 7]
test3 = ["more stuff", 1, 4, 99]
int_list = []
I know that I can do the following code to append all integers to a new list:
for elem1, elem2, elem3 in zip(test1, test2, test3):
if elem1 is int:
int_list.append(elem1)
if elem2 is int:
int_list.append(elem2)
if elem3 is int:
int_list.append(elem3)
Is there anyway that I can merge the if statements into one conditional statement? Or make it less code? Is there a more pythonic way to do this? I tried doing the following code, but it would include elements that were not integers:
for elem1, elem2, elem3 in zip(test1, test2, test3):
if (elem1 is int, elem2 is int, elem3 is int):
int_list.append(elem1)
int_list.append(elem2)
int_list.append(elem3)
Upvotes: 1
Views: 1257
Reputation: 476594
There are some problems with your code:
zip
constructs tuples of elements as long as all lists have elements, if one of the lists is exhausted, zip
stops;elem1 is int
does not do type-checking, it does reference equality checking, you can use isinstance(..)
for that; andif (...)
will always succeed since you test it with a tuple with one or more elements: regardless of the values of that tuple the truthiness is True
.Why not first join them thogether? You can for instance use a tuple of the lists, like:
for sublist in (test1,test2,test3):
for x in sublist:
if isinstance(x,int):
int_list.append(x)
Or you can use list comprehension:
int_list = [x for sublist in (test1,test2,test3)
for x in sublist if isinstance(x,int)]
Upvotes: 2
Reputation: 2200
You use zip
, but you want itertools.chain()
. Additionally you should use isinstance
to check class membership.
from itertools import chain
for elem in chain(test1, test2, test3):
if isinstance(elem, int):
int_list.append(elem)
Upvotes: 2