Python – Append given number with every element of the list


When it is required to append given number with every element of the list, a list comprehension is used.

Example

Below is a demonstration of the same

my_list = [25,36, 75, 36, 17, 7, 8, 0]

print ("The list is :")
print(my_list)

my_key = 6

my_result = [x + my_key for x in my_list]

print ("The resultant list is :")
print(my_result)

Output

The list is :
[25, 36, 75, 36, 17, 7, 8, 0]
The resultant list is :
[31, 42, 81, 42, 23, 13, 14, 6]

Explanation

  • A list is defined and is displayed on the console.

  • An integer value for key is defined.

  • Using list comprehension, the element in the list and the integer value are added, and stored in a list.

  • This is assigned to a variable.

  • This is displayed as output on the console.

Updated on: 14-Sep-2021

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements