HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Add element alternatively to a list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listalternativelyelementadd

Problem

I want to place an element alternatively between any two elements of a list.

l1 = list('abcde')
fill = 'z'


How it should look like:

['a', 'z', 'b', 'z', 'c', 'z', 'd', 'z', 'e']


My solution:

fill = 'z'
l2 = [fill]*(len(l1)-1)
[x for t in map(None, l1, l2) for x in t if x]


Is there a better approach, i.e. that doesn't need to create another list?

Solution

What if fill were a comma? Does that remind you of a common string-handling idiom?

>>> ','.join('abcde')
'a,b,c,d,e'


The only remaining task is to convert that result into a list.

Therefore, the solution would be better written as:

list(fill.join(l1))

Code Snippets

>>> ','.join('abcde')
'a,b,c,d,e'
list(fill.join(l1))

Context

StackExchange Code Review Q#115050, answer score: 7

Revisions (0)

No revisions yet.