Open In App

Python – Append given number with every element of the list

Improve
Improve
Like Article
Like
Save
Share
Report

In Python, lists are flexible data structures that allow us to store multiple values in a single variable. Often, we may encounter situations where we need to modify each element of a list by appending a given number to it. Given a list and a number, write a Python program to append the number with every element of the list.

Input: [1,2,3,4,5]
Key: 5
Output: [1,5,2,5,3,5,4,5,5,5]
Explanation: In this, we have append the number '5' after every element of the list in Python.

Add Number with Every Element in Python

Here are different methods listed below to append a given number with every element of the list:

Python Append Number using For Loop

Using a for loop to cycle through the list and edit each element is one technique to append a specified number to every element. Here is a sample of the code.

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]

Time complexity: O(n)
Space complexity: O(n)

Python Append Number using List Comprehension

A succinct method for carrying out actions on each list element is provided by list comprehension. By adding the specified number to each member, we may utilize it to build a new list. Here’s an illustration:

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]

Time Complexity: O(n)
Space Complexity: O(n)

Add Elements to a List using For Loop

To store the modified components, create a list that is empty. Use the zip() function to iterate through the list’s elements and the supplied number. Add the altered element to the newly created list.

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]

Time Complexity: O(n)
Space Complexity: O(n)

Add Integer to a List in Python using List() Method

Use the map() function along with str() to convert the list’s elements to strings. To combine the strings into one string, use the join() method. Include the specified number after the string. Using the split() method, split the modified string back into a list.

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]

Time complexity: O(n) 
Space complexity: O(n)

Python Append Number using Recursive Method

The recursive_method function takes two inputs, an input_list of integers and a key integer. It first checks if the input_list is empty or not. If it is empty, it returns an empty list. If it is not empty, it takes the first element of the input_list, adds it to the key, and creates a new list with these two elements. It then recursively calls the recursive_method function on the rest of the input_list (i.e., input_list[1:]) and concatenates the result of this recursive call to the new list it created earlier. This process continues until the entire input_list has been processed.

Python3




def recursive_method(input_list, key):
    if not input_list:
        return []
    else:
        return [input_list[0], key] + recursive_method(input_list[1:], key)
input_list = [1, 2, 3, 4, 5]
key = 7
result = recursive_method(input_list, key)
print(result)


Output

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

The time complexity of this recursive_method function is O(n), where n is the length of the input_list. This is because, for each element in the input_list, the function performs a constant amount of work (i.e., creating a list with two elements and making a recursive call on a sublist of length n-1). Therefore, the total number of operations is proportional to the length of the input_list.
The auxiliary space of this function is also O(n), because, at each recursive call, a new list is created and stored in memory. The maximum number of recursive calls that can be made is equal to the length of the input_list, so the total amount of space used is proportional to the length of the input_list

Python Append Number Using Pandas

Import the Pandas library. Convert the list to a Pandas Series object. Use the + operator to add the specified number to the Series object.

Python3




import pandas as pd
 
input = [1, 2, 3, 4, 5]
key = 7
 
df = pd.DataFrame({'col': input})
result = df['col'].apply(lambda x: [x, key]).sum()
 
print(result)


Output

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

Time complexity: O(n)
Space complexity: O(n)

Python Append Number Using Numpy

In Python, you can use the NumPy library to efficiently append a given number to every element of a list.

Python3




import numpy as np
 
input_list = [1, 2, 3, 4, 5]
key = 7
 
input_array = np.array(input_list)
new_array = np.empty((input_array.size, 2))
 
# Set the first dimension to be the input array and the second dimension to be the key
new_array[:, 0] = input_array
new_array[:, 1] = key
 
# Flatten the new array to get the desired output
result = list(map(int,new_array.flatten().tolist()))
 
print(result)


Output

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

Time complexity: O(n), where n is the length of the input list. This is because converting the input list to a NumPy array and flattening the new array both take O(n) time.
Space complexity: O(n), where n is the length of the input list. This is because the new array takes O(n) space.



Last Updated : 25 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads