Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat list object n times

Tags:

r

This seems like an easy one (and it probably is), but since I'm braindead, I'm ready to get on the shame wall.

How to copy a list object n times, and wrap it up in a list afterwards? Something like this:

list(foo = "", bar = 0) 

in order to get:

list(     list(foo = "", bar = 0),     list(foo = "", bar = 0)     ) 


NOTE: for loops are considered cheating
like image 988
aL3xa Avatar asked Dec 06 '11 20:12

aL3xa


People also ask

How do you repeat a list and times?

To repeat the elements of the list n times, we will first copy the existing list into a temporary list. After that, we will add the elements of the temporary list to the original list n times using a for loop, range() method, and the append() method.

How do I make a list of the same values?

Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 . The result of the expression will be a new list that contains the specified value N times. Copied!

How do you replicate a list?

The replication of list of a list can be created by using rep function. For example, if we have a list called x and we want to create five times replicated list of this list then we can use the code rep(list(x),5).

How do I make a list of time in Python?

To create a list with a single item repeated N times with Python, we can use the * operator with a list and the number of items to repeat. We define my_list by using an list and 10 as an operand to return a list with 'foo' repeated 10 times.


1 Answers

Well, rep works (and is "vectorized") if you simply wrap the list in another list...

x <- list(foo = "", bar = 0) rep(list(x), 2) 

That trick can also be used to assign NULL to an element in a list:

x[2] <- list(NULL) 
like image 71
Tommy Avatar answered Sep 30 '22 10:09

Tommy