Skip to content
Related Articles

Related Articles

Python – Append given number with every element of the list

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Jul, 2022

Given a list and a number, write a Python program to append the number with every element of the list.

Examples:

input = [1,2,3,4,5]

key = 5 (number to be appended)

output = [1,5,2,5,3,5,4,5,5,5]

The following are ways to achieve this functionality:

Method 1: Using for loop

Python




input = [1, 2, 3, 4, 5]
key = 7
 
result = []
for ele in input:
    result.append(ele)
    result.append(key)
 
print(result)

Output:

[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]

Method 2: Using list comprehension and itertools.chain

Python




import itertools
 
input = [1, 2, 3, 4, 5]
key = 7
 
result = list(itertools.chain(*[[ele, key] for ele in input]))
 
print(result)

Output:

[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]

Method 3: Using zip and for loop

Python




input = [1, 2, 3, 4, 5]
key = 7
 
result = []
for x, y in zip(input, [key]*len(input)):
    result.extend([x, y])
 
print(result)

Output:

[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]

Method 4: Using list(),map(),str(),join() and split()

Python3




input = [1, 2, 3, 4, 5]
key = 7
 
l=list(map(str,input))
p="*"+str(key)+"*"
x=p.join(l)
a=x.split("*")
res=list(map(int,a))
res.append(key)
 
print(res)

Output

[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!