Home > Software design >  How to copy the elements of the list within the list?
How to copy the elements of the list within the list?

Time:03-03

I have a list list_1 = [[1,2,3], [4,5,6], [7,8,9], ....]. I want [[1,2,3], [1,2,3], [4,5,6], [4,5,6], [7,8,9], [7,8,9]]. How can i achieve this? Its like basically copying each element of the list to its consecutive index.

CodePudding user response:

from copy import deepcopy

def multiply_list_elem(lst, n):
    out = list()
    for elem in lst:
        for _ in range(n):
            out.append(deepcopy(elem))
    return out

if __name__ == '__main__':
    list_1 = [[1,2,3], [4,5,6], [7,8,9]]
    print(multiply_list_elem(list_1, 2))

CodePudding user response:

You can use this as iterative process:

list_1 = [[1,2,3], [4,5,6], [7,8,9]]
list_2 = []
for element in list_1:
  for times in range(2):
    list_2.append(element)

Or this for list comprehension:

CodePudding user response:

First declare another list double and then modify double with two elements for each element of lst.
You can remove the lst = double statement, if you don't want to modify the original list.

Sample code:

def multiply(lst):
    double = [];
    for i in lst:
        for j in range(2):
            double.append(i);
    lst = double;
    return lst;

CodePudding user response:

You could double the list, then sort based on the first index of the sublists:

list_1 = [[1,2,3], [4,5,6], [7,8,9]]

list_2 = sorted(list_1 * 2, key = itemgetter(0))

CodePudding user response:

The easiest solution would be something like:

def double(some_list): 
    return_list = [] 
    for element in some_list: 
             return_list.append(element) 
             return_list.append(element) 
    return return_list

using the second for loop can be done, but is slower. Therefore I recommend not using it unless you want to have a variable multiplier as presented in Félix Herbinet's solution.

  • Related