Python – Append given number with every element of the list
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 = 7result = []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 itertoolsinput = [1, 2, 3, 4, 5]key = 7result = 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 = 7result = []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 = 7l=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]






Please Login to comment...