[BangPypers] List of n but same objects
Noufal Ibrahim KV
noufal at nibrahim.net.in
Thu Dec 11 11:56:50 CET 2014
On Thu, Dec 11 2014, Rajiv Subramanian M wrote:
> 1. How in the first case i.e [iter(x)] * 3 creates a list of 3 but the
> same objects?
The * operator when applied to a list (or any sequence type) is a
repetition. You can see the code for list_repeat here . The line I've
linked to shows what's happening. You allocate enough memory for a new
list that's large enough and copy over stuff from the source to the
target those many times.
Multiplying a list by `n` returns a new list with each element of the
said list repeated `n` times.
> 2. Is there any other possibility or way (like * operator does here) by
> which we can obtain the same result as in CASE 1?
You could do something like this.
x = range(10)
[iter(x) for x in range(3)]
This will call 3 iter times and give you 3 separate iterators. I think
though that you're doing something wrong here. What's the larger problem
you're trying to solve?
> 3. Does only list and listiterators objects can behave this way? what other
> python datatypes can behave this way?
This the semantics of sequence types. I haven't checked for tuples
etc. but the list sequence methods behave this way. I don't think the
others will be different. It doesn't make sense to make copies of the
original thing anyway. You can do that explicitly using copy or
something if you want to.
More information about the BangPypers