Skip to content
Related Articles

Related Articles

Improve Article

Python – Append given number with every element of the list

  • Last Updated : 26 Nov, 2020

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]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :