473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

A query about list

Hello everybody,

I am very new to python. I have a query about
list in python.

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?

Regards,
Santanu
Jul 18 '05 #1
13 2624
In article <pa****************************@softhome.net>, Santanu Chatterjee wrote:
I am very new to python. I have a query about
list in python.

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?


Normally, I'd suggest "reduce(operator.add, ...)" to flatten a list, but
since you've got some "naked" entries, that won't work...

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]

Dave

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #2
Santanu Chatterjee wrote:
Hello everybody,

I am very new to python. I have a query about
list in python.

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?


Why do you have such a data structure in the first place? Can't it be
avoided?

If for example you made the mistake of .append()-ing lists to a list,
then you can .extend() it instead.

-- Gerhard

Jul 18 '05 #3
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
Jul 18 '05 #4
In article <pa****************************@softhome.net>, Santanu Chatterjee wrote:
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 ?


Ahh, I see what you mean, now. You probably want slice assignment.

Try, for starters:
a[1:2] = a[1]

You'll probably still need to use type().

Dave

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #5
In article <sl******************@lackingtalent.com>, Dave Benjamin wrote:
In article <pa****************************@softhome.net>, Santanu Chatterjee wrote:
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 ?


Ahh, I see what you mean, now. You probably want slice assignment.

Try, for starters:
a[1:2] = a[1]

You'll probably still need to use type().


This *seems* to work, but I have a sneaking feeling there's a bug in here as
a result of the slice assignment. I haven't been able to find a boundary
case that breaks this, but it seems like the slice assignment would mess up
the indexes in the loop. Can anyone find a way to either break or improve
this?
a = [1, [2, 3, 4], 5, 6, 7, [8, 9, 10], 11, 12]
def flatten_sublists(lst): .... for i, item in enumerate(lst):
.... if type(item) is type([]):
.... lst[i:i+1] = lst[i]
.... flatten_sublists(a)
a

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #6
On Thu, 09 Oct 2003 21:19:18 +0000, Dave Benjamin wrote:
In article <pa****************************@softhome.net>, Santanu
Chatterjee wrote:
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 ?


Ahh, I see what you mean, now. You probably want slice assignment.

Try, for starters:
a[1:2] = a[1]

You'll probably still need to use type().


Yes, this is what I wanted.
Thanks for this simple solution.

Regards,
Santanu
Jul 18 '05 #7
On Thu, 09 Oct 2003 22:17:25 +0200, Gerhard Häring wrote:
Why do you have such a data structure in the first place? Can't it be
avoided?


Well, maybe, but I was trying to get an entire file into a list with
the ASCII values of the characters in binary form (not actually 'binary'
but as a list containing 8 1s and 0s) as its contents, then expand the
lists in place to get a long stream of 1s and 0s for some mathematical
operation.
Dave provided a simple solution which should have occurred to me in the
first place :)

Thanks, anyway.

Regards,
Santanu
Jul 18 '05 #8

"Dave Benjamin" <ra***@lackingtalent.com> wrote in message
news:slrnbobkr7.io6.ra***@lackingtalent.com...
This *seems* to work, but I have a sneaking feeling there's a bug in here as a result of the slice assignment. I haven't been able to find a boundary case that breaks this, but it seems like the slice assignment would mess up the indexes in the loop. Can anyone find a way to either break or improve this?


I believe enumerate is a generator which makes one pair at a time, as
needed. If so, then you are iterating over inserted items after the
first, which may or may not be what is wanted. I believe an empty
sublist would be deleted, shifting remainder to left and skipping next
item. Try [1, [], [2,3,5]] and also [[[1,2],3], [4,[5,6]]]
a = [1, [2, 3, 4], 5, 6, 7, [8, 9, 10], 11, 12]
def flatten_sublists(lst): ... for i, item in enumerate(lst):
... if type(item) is type([]):
... lst[i:i+1] = lst[i]
... flatten_sublists(a)
a

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


If my hypothesis is correct, I might rewrite with while i loop to
either iterate over either all (for multilevel flatten) or none (for
two-level flatten) of inserted items.

Terry J. Reedy
Jul 18 '05 #9
Dave Benjamin wrote:
In article <sl******************@lackingtalent.com>, Dave Benjamin wrote:
In article <pa****************************@softhome.net>, Santanu
Chatterjee wrote:
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 ?


Ahh, I see what you mean, now. You probably want slice assignment.

Try, for starters:
a[1:2] = a[1]

You'll probably still need to use type().


This *seems* to work, but I have a sneaking feeling there's a bug in here
as a result of the slice assignment. I haven't been able to find a
boundary case that breaks this, but it seems like the slice assignment
would mess up the indexes in the loop. Can anyone find a way to either
break or improve this?
a = [1, [2, 3, 4], 5, 6, 7, [8, 9, 10], 11, 12]
def flatten_sublists(lst): ... for i, item in enumerate(lst):
... if type(item) is type([]):
... lst[i:i+1] = lst[i]
... flatten_sublists(a)
a

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Here's a variant that might interest you. It entirely omits indices and
slices and can deal with recursively nested sequences.
You need not create a list at all, if you want to iterate over the elements
one at a time.

<code>
def flatten(seq):
""" Flatten a sequence of sequences of sequences...
"""
# avoid infinite recursion with strings
if isinstance(seq, basestring):
yield seq
else:
try:
for i in seq:
for k in flatten(i):
yield k
except TypeError:
yield seq

# seems to work with the borderline cases
assert list(flatten([1,[2,[3,4]],5,6,7,[8,9,10],11,12])) == range(1, 13)
assert "ABCDEFGHIJKL" == "".join(
flatten(["A", ["B", ["C", "D"]], "E", "F", "G", ["H", "I", "J"], "K",
"L"]))
assert list(flatten([1, [], [2,3,4,5]])) == range(1, 6)
assert list(flatten([[[1,2],3], [4,[5,6]]])) == range(1, 7)
assert list(flatten([[]])) == []
assert list(flatten([])) == []

# but beware of infinite iterators anywhere in your tree...
#from itertools import count
#for i in flatten(count()): print i
</code>

Peter
Jul 18 '05 #10
Hi, Peter!

In article <bm*************@news.t-online.com>, Peter Otten wrote:
Here's a variant that might interest you. It entirely omits indices and
slices and can deal with recursively nested sequences.
You need not create a list at all, if you want to iterate over the elements
one at a time.

def flatten(seq):
""" Flatten a sequence of sequences of sequences...
"""
...


Nice work! I've occasionally used a flatten after a bunch of list processing
because it made a sequence of not-quite-parallel operations seem more
parallel. I saw it as unfortunate that I was creating all of these extra
lists, but it seemed a fair tradeoff between clarity and efficiency. I think
your example shows that if I had only understood laziness better (hehe) I
might not have had to make a tradeoff at all.

Thanks,
Dave

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #11
Santanu Chatterjee wrote:

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.


Executing _any_ statement is time consuming. The question is
how much time it consumes, though, right? Certainly creating
a list is a fairly simple operation in Python, and I think
you should focus more on readability and functionality (making
it work) rather than worrying about performance issues right
now. Also, modifying something in-place tends to be more
error-prone and dangerous than building a new item from pieces
of the old (e.g. when doing multi-threaded stuff, you could
access an inconsistent view of something). Better just to
go with the typical Python meaning of "simpler", which has
nothing to do with whether something creates new objects. :)

-Peter
Jul 18 '05 #12
Dave Benjamin wrote:
...
Normally, I'd suggest "reduce(operator.add, ...)" to flatten a list, but
It would be an utter waste anyway, in Python 2.3. The sum() builtin
is quite a bit faster, as well as obviously simpler.
since you've got some "naked" entries, that won't work...


Yeah, there's the rub, of course. But I don't think I have anything
to add to the many ideas you and others have proposed on this;
just wanted to point out sum's existence and preferability;-).
Alex

Jul 18 '05 #13
In article <JT**********************@news2.tin.it>, Alex Martelli wrote:
since you've got some "naked" entries, that won't work...


Yeah, there's the rub, of course. But I don't think I have anything
to add to the many ideas you and others have proposed on this;
just wanted to point out sum's existence and preferability;-).


Hey, I didn't even think of that. Lots of little goodies in 2.3. =)

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: John Macon | last post by:
------=_NextPart_000_04B4_01C36308.415CE100 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, Long time reader, first time poster, I hope...
3
by: Nick Truscott | last post by:
<? // scoreinput.php - input a match score when match selected from list ?> <html> <head> <basefont face="Verdana"> </head> <body>
3
by: John young | last post by:
I have been looking for an answer to a problem and have found this group and hope you can assist . I have been re doing a data base I have made for a car club I am with and have been trying to...
2
by: ormy28 | last post by:
I really need some help with the following problem if anyone would be willing. I need a list box to list the opposite of what appears in a query. Heres the details: My database is for a...
0
by: starace | last post by:
I have designed a form that has 5 different list boxes where the selections within each are used as criteria in building a dynamic query. Some boxes are set for multiple selections but these list...
2
by: Zlatko Matiæ | last post by:
Hello. How to reference selected values from a multi-select list box, as a criteria in a query ? Is it possible at all? Regards, Zlatko
36
by: Liam.M | last post by:
hey guys, I have one last problem to fix, and then my database is essentially done...I would therefore very much appreciate any assistance anyone would be able to provide me with. Currently I...
0
by: Chuck36963 | last post by:
Hi all, I've been working on a listing problem and I can't figure out how to work it out. I have looked far and wide on the web to find answers, but I'd like other peoples input on my project in...
3
by: rhobson2 | last post by:
Hello, I wrote a database applicaiton using Access XP (2002) and everything has been working good for the client until they purchased a couple of new computers with Access 2003. The meetings...
1
by: Nettle | last post by:
Purpose: This is a Distribution List database. Function: Users create many different email distribution lists, tailoring each to fit their specific needs Wanted: Users can combine...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.