-1

How do I duplicate the elements in a list? Without returning any value or even changing the order of the list?

for example I have defined a function with an argument:

def func1(list1):

  • func1 is supposed to modify list1 so that each element appears twice without changing the order of the list itself

like this:

In: list1 = [342, 548, 23, 321, 555]

In: func1(list1)

In: list1

Out: [342, 548, 23, 321, 555, 342, 548, 23, 321, 555]

And thank you so much in advance!

  • 1
    `output = list1 + list1` ? I'm not sure if this is what you are asking, but that will concatenate 2 lists, essentially duplicating itself once – Sam Apr 15 '18 at 14:44
  • What I mean is that I would like the function to modify the list in the argument so that each element appears twice without changing the order of list itself – Jonathan Payne Apr 15 '18 at 14:50
  • 1
    @JonathanPayne there is no need to delete your post in codereview.stackexchange.com. the comments should guide you to improve the post so that other users are motivated the review your code. Downvotes only show that there are some users that find your post not good at the moment. This should not frustrate you but only sho that the post should be improved. You can undelete it and improve it, if you want. – miracle173 May 10 '18 at 09:17
  • Possible duplicate of [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – Mast May 10 '18 at 09:40

5 Answers5

2
def func1(list1):
    list1.extend(list1)
FMc
  • 41,963
  • 13
  • 79
  • 132
1
In [47]: list1 = [342, 548, 23, 321, 555]

In [48]: list1*2
Out[48]: [342, 548, 23, 321, 555, 342, 548, 23, 321, 555]
Roushan
  • 4,074
  • 3
  • 21
  • 38
0

We can use list[:] = other_list to reassign the contents of a list. list*2 will give us the entire list twice

def func1(inlist):
    inlist[:] = inlist*2
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0
def func1(list1):
    list1 = list1 * 2
    print(list1)

list1 * 2 will duplicate the values of list at the end in the order

0

Best way is :

list_2=list1*2
print(list_2)

other way you can also use itertools cycle :

final_result=[]
count=0
for i in itertools.cycle(list1):
    count+=1
    if count==2*len(list1)+1:
        break

    final_result.append(i)
print(final_result)

output:

[342, 548, 23, 321, 555, 342, 548, 23, 321, 555]
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88