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 ))
new_array[:, 0 ] = input_array
new_array[:, 1 ] = key
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. Example Input: [1, 2, 3.5, geeks, for, geeks, -11]Output: 7 Let's explore various ways t
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 t
3 min read
Append Element to an 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
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,
5 min read
Python - List Elements with given digit
Given list of elements and a digit K, extract all the numbers which contain K digit. Input : test_list = [56, 72, 875, 9, 173], K = 5 Output : [56, 875] Explanation : 56 and 875 has "5" as digit, hence extracted. Input : test_list = [56, 72, 875, 9, 173], K = 4 Output : [] Explanation : No number ha
6 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
Python - Append Multiple elements in set
In Python, sets are an unordered and mutable collection of data type what does not contains any duplicate elements. In this article, we will learn how to append multiple elements in the set at once. Example: Input: test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]Output: {1, 2, 4, 5, 6, 7, 9, 10}Expla
4 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list
8 min read
Python | Return new list on element insertion
The usual append method adds the new element in the original sequence and does not return any value. But sometimes we require to have a new list each time we add a new element to the list. This kind of problem is common in web development. Let's discuss certain ways in which this task can be perform
5 min read