Python - Append given number with every element of the list
Last Updated :
25 Jul, 2023
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.
Similar Reads
How to Get the Number of Elements in a Python List
In Python, lists are one of the most commonly used data structures to store an ordered collection of items.In this article, we'll learn how to find the number of elements in a given list with different methods.ExampleInput: [1, 2, 3.5, geeks, for, geeks, -11]Output: 7Let's explore various ways to do
3 min read
Create List of Numbers with Given Range - Python
The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8
3 min read
Python - Move Element to End of the List
We are given a list we need to move particular element to end to the list. For example, we are given a list a=[1,2,3,4,5] we need to move element 3 at the end of the list so that output list becomes [1, 2, 4, 5, 3].Using remove() and append()We can remove the element from its current position and th
3 min read
Append Elements to Empty List in Python
In Python, lists are used to store multiple items in one variable. If we have an empty list and we want to add elements to it, we can do that in a few simple ways. The simplest way to add an item in empty list is by using the append() method. This method adds a single element to the end of the list.
2 min read
Create a List of Tuples with Numbers and Their Cubes - Python
We are given a list of numbers and our task is to create a list of tuples where each tuple contains a number and its cube. For example, if the input is [1, 2, 3], the output should be [(1, 1), (2, 8), (3, 27)].Using List ComprehensionList comprehension is one of the most efficient ways to achieve th
3 min read
Python | Replace list elements with its ordinal number
Given a list of lists, write a Python program to replace the values in the inner lists with their ordinal values. Examples:Input : [[1, 2, 3], [ 4, 5, 6], [ 7, 8, 9, 10]]Output : [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]]Input : [['a'], [ 'd', 'e', 'b', 't'], [ 'x', 'l']]Output : [[0], [1, 1, 1, 1], [2, 2
5 min read
Python - Ways to format elements of given list
Formatting elements of a list is a common requirement especially when displaying or preparing data for further processing. Python provides multiple methods to format list elements concisely and efficiently. List comprehension combined with Python f-strings provides a simple and efficient way to form
2 min read
Add Elements of Two Lists in Python
Adding corresponding elements of two lists can be useful in various situations such as processing sensor data, combining multiple sets of results, or performing element-wise operations in scientific computing. List Comprehension allows us to perform the addition in one line of code. It provides us a
3 min read
Python Program to replace list elements within a range with a given number
Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is u
3 min read
Python program to insert an element into sorted list
Inserting an element into a sorted list while maintaining the order is a common task in Python. It can be efficiently performed using built-in methods or custom logic. In this article, we will explore different approaches to achieve this.Using bisect.insort bisect module provides the insort function
2 min read