How to separate each element from a list, with a String, on a line

0

The problem is simple, I'd like to add an element to a real-time generated list for each given iteration. For example, if list 1 is generated through [x for x in range(10) if x%2==0] , then I want the 'a' character to appear between each element in the list. That is, list 1 would be [0, 'a', 2, 'a', 4, 'a', 6, 'a', 8]. To resolve this problem there are two restrictions: use only the default library and use list comprehension.

What I've tried so far: link

However, this solution solves the problem by using sublists.

Purpose:

My working language is currently Python, but I have invested some time learning Clojure. In this purely functional language, this task would be solved as follows:

(->> (range 10)(filter even?)(interpose "a") )

I would like to know how to solve this problem in an elegant and pythonic way:)

    
asked by anonymous 03.06.2018 / 20:32

1 answer

2

Just change the position of the conditional and use what in Python is basically a ternary operator:

lista = [x if x % 2 == 0 else 'a' for x in range(10)]

The value of x will be [0, 10 [ including it in the list if it is even, otherwise the 'a' character is inserted. The result will be:

[0, 'a', 2, 'a', 4, 'a', 6, 'a', 8, 'a']
    
04.06.2018 / 00:58