Simple question of Python? Interconnect different values of different lists

I have these lists:
value = (0,1,0)
x = [‘a1’,‘a2’,‘a3’]
y = [‘b1’,‘b2’,‘b3’]

I know if I do this:


<i>a = []</i>
<i>id = -1</i>
<i>for i in value:</i>
<i>    id += 1</i>
<i>    if i == 1:</i>
<i>        a.append(x[id])</i>
<i>    else:</i>
<i>        a.append(y[id])
</i>

I obtain a list like this:
a == [‘b1’, ‘a2’, ‘b3’]

But how can I do this in a simpler way? And preferably on one line and without using the “id”.

To get rid of the manual index, you can use the enumerate function:


<i>values = (0,1,0)
</i><i>x = ['a1','a2','a3']</i>
<i>y = ['b1','b2','b3']</i>

a = []
for index,value in enumerate(values):
    if value == 1:
        a.append(x[index])
    else:
        a.append(y[index])

I’d advise against using ‘id’ as a variable name, because that is already a builtin function.

To turn the whole thing into a single pure expression, you can use a conditional expression and a list comprehension:


<i>values = (0,1,0)
</i><i>x = ['a1','a2','a3']</i>
<i>y = ['b1','b2','b3']
</i>
a = [(x[index] if value==1 else y[index]) for index,value in enumerate(values)]

Whether to consider this form “simpler” is a matter of taste, I guess.

Cool! @BeerBaron, you’re the man! Thank U
I’m learning to use the builtin functions.

You can slim down Baron’s single-liner to:

[pair[i%2==0] for i, pair in enumerate(zip(a,b))] # ['b1', 'a2', 'b3']

Or if x has either the same length or one element more as y, you can do even simpler:

x[::2] = y[::2] # result in x

Cool!! I’m still trying to understand the first. But just remembering, the resulting list should relate to the sequence “value”.
Ex: If value = (1,1,0)
a =
[‘a1’, ‘a2’, ‘b3’]


&gt;&gt;&gt; value = (0,1,0)
&gt;&gt;&gt; x = ['a1','a2','a3']
&gt;&gt;&gt; y = ['b1','b2','b3']
&gt;&gt;&gt; [xp if vp else yp for xp, yp, vp in zip(x, y, value)]
['b1', 'a2', 'b3']
&gt;&gt;&gt; value = (1,1,0)
&gt;&gt;&gt; [xp if vp else yp for xp, yp, vp in zip(x, y, value)]
['a1', 'a2', 'b3']

Choose from x or y depending on value in the value list. Which is not what your original code does but what you say. Here I assume that if value is True you want from x otherwise from y.

Yeah. good solution @Linusy also has solved the question:

So, the thread was solved :slight_smile:
But, lower solution = better solution. So I’m still in favor of new solutions.

Oh, missed that “value” defines from which list to pick. Here’s a corrected version:

[pair[not value[i]] for i, pair in enumerate(zip(a,b))]