# list iteration if statement

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jan 3 03:47:44 CET 2009

```On Sat, 03 Jan 2009 01:52:04 +0000, alex goretoy wrote:

> Hello All,
>
> I'm doing this in my code
>
> [[v.append(j) for j in i] for i in self.value]
>
> if works and all,

Replacing "self.value" with a list of lists of ints:

>>> list_of_lists = [[1, 2, 3], [2, 4, 6]]
>>> v = []
>>> output = [[v.append(j) for j in sublist] for sublist in list_of_lists]
>>> v
[1, 2, 3, 2, 4, 6]
>>> output
[[None, None, None], [None, None, None]]

So you create two lists, one is a copy of self.value which has been
flattened, and the other is a nested list of nothing but None. What a
waste of effort if your input is large.

Why not just do the obvious for loop?

v = []
for L in list_of_lists:
for item in L:
v.append(item)

> but I need to add a if statement in the mix.

Using a for loop, it should be obvious:

v = []
for L in list_of_lists:
for item in L:
if item != 0: v.append(item)

> Can't
> seem to remember the syntax to do so and everything I've tried seems to
> fail.

If you *insist* on doing it the wrong way,

[[v.append(j) for j in i if j != 0] for i in self.value]

> How do I add a check to see if j is not int("0") then append to v
> list? Thank you in advance. -A

Is there some significance of you saying int("0") instead of 0?

--
Steven.

```