'Python help: how to space place "_" between every number in a list [closed]

So I basically need a function or a block of code that can essentially turn a list in a form like this e.g. [1,2,3,4,5] into something like this, ["__ ", "1", "__ ", "2" , "__ " , "3" , "__ ", 4, "__ ", 5, "__"] but I don't know how to do that in python. Basically, I need to put dashes in between every number and at the end and start of the list. Any ideas?



Solution 1:[1]

Something like this

list = [1,2,3,4,5]
list2 = ["__"]

for i in range(len(list)):
    list2.append(list[i])
    list2.append("__")

print(list2)

Solution 2:[2]

Use chain.from_iterable from itertools to flatten nested list created by zip:

from itertools import chain

>>> list(chain.from_iterable(zip(l, ['__ '] * len(l))))
[1, '__ ', 2, '__ ', 3, '__ ', 4, '__ ', 5, '__ ']

Solution 3:[3]

l = [1, 2, 3, 4, 5]
m = ['__ '] * (2 * len(l))
m[::2] = l

is Cool

Solution 4:[4]

Works with any list

Code:

list = [1,2,3,4,5]
tick = 0

def underscore(list):
    global tick
    for i in range(len(list) * 2):
        if tick == 0:
            tick = 1
        elif tick == 1:
            tick = 0
            list.insert(i,'_')
        print(list)
underscore(list = list)

Output:

[1, 2, 3, 4, 5]
[1, '_', 2, 3, 4, 5]
[1, '_', 2, 3, 4, 5]
[1, '_', 2, '_', 3, 4, 5]
[1, '_', 2, '_', 3, 4, 5]
[1, '_', 2, '_', 3, '_', 4, 5]
[1, '_', 2, '_', 3, '_', 4, 5]
[1, '_', 2, '_', 3, '_', 4, '_', 5]
[1, '_', 2, '_', 3, '_', 4, '_', 5]
[1, '_', 2, '_', 3, '_', 4, '_', 5, '_']

You could probably add a return statement in the function.

Solution 5:[5]

This works with any rule you set: __ and number or number and __, etc.

def addcharacter(l):
    simplelist=[]
    # rule: ["__",x]
    v= [["__",x] for x in l]
    for i in v:
        for j in i:
            simplelist.append(j)
    return simplelist

result=addcharacter([1,2,3,4])
print(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob
Solution 2
Solution 3
Solution 4 Blue Robin
Solution 5 walther leonardo