+

Python | Returning a new list when inserting an item

Method # 1: Using the + operator
This task can be accomplished if we compose a single list of items and combine the original list with this newly created list of one item.

# Python3 demo code
# return a new list when an element is inserted
# using the + operator

 
# initializing list

test_list = [ 5 , 6 , 2 , 3 , 9 ]

 
# print the original list

print ( "The original list is:" + str (test_list))

 
# element to add

K = 10

  
# using the + operator
# return a new list when an element is inserted

res = test_list + [K]

 
# print result

print ( "The newly returned added list:" +   str (res))

Output:

 The original list is: [5, 6, 2, 3, 9] The newly returned added list: [5, 6, 2, 3, 9, 10] 

Method # 2: Using the * Operator
This kind of task can be used with the * operator, in which we use the * operator to take all the elements and also add a new element to display a new list.

# Python3 demo code
# return a new list when an element is inserted
# using the * operator

< p>  
# initializing list

test_list = [ 5 , 6 , 2 , 3 , 9 ]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# element to add

K  = 10

 
# using the * operator
# return a new list when an element is inserted

res = [ * test_list, K]

 
# print result

print ( "The newly returned added list:" +   str (res))

Output:

 The original list is: [5, 6, 2, 3, 9] The newly returned added list: [5, 6, 2, 3, 9, 10] 
Get Solution for free from DataCamp guru