A query about list

Santanu Chatterjee santanu at softhome.net
Thu Oct 9 17:16:22 EDT 2003


On Thu, 09 Oct 2003 20:05:08 +0000, Dave Benjamin wrote:

>> Suppose I have a list
>> a = [1,[2,3,4],5,6,7,[8,9,10],11,12]
>> I want to know if there is any simple python facility available that
>> would expand the above list to give
>> a = [1,2,3,4,5,6,7,8,9,10,11,12]
>> 
>> I know I can do that with a type() and a for/while loop, but is there
>> any simpler way?

> I don't know if you consider this simpler, but you could define a
> reduction function that checks the type of the second argument, and use it
> like this:
> 
>>>> def merge(x, y):
> ...     if type(y) is type([]): return x + y 
> ...     return x + [y]
> ...
>>>> reduce(merge, a, [])
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Thanks for the quick reply. Yes, this is similar to what I would do
using for loop. 

But by 'simpler' what I really meant was that manipulating
the list 'a' itself without creating a new list object.
I read that creating new objects is time consuming (and that it is
better to use fill a list and then 'join' to create a string, than to
increase a string using += ). Sorry I forgot to mention it before.

I was trying something like a.insert(1,a.pop(1)) but I need to
modify a.pop(1) somehow so that the brackets vanish ...you know
what I mean. Is that possible ? 

Regards,
Santanu




More information about the Python-list mailing list