473,545 Members | 2,095 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

disgrating a list

Hello,

How can I disgrate (probably not a good word for it) a list? For
example:

a = [1,2]
b = 3
c = [a] + [b] # which makes [[1,2],3]

Then how can I change c ([[1,2],3]) into [1,2,3]? I have a simple
function for this:
=============== =========
def flatten(l):
r = []
s = [l]
while len(s) 0:
i = s.pop()
if i.__class__ == list:
for c in i:
s.append(c)
else:
r.append(i)
return r
=============== =========
But this function isn't really doing it in the "python-way". Doesn't
have python an obscure function or buildin to do this?

Greetz,

Noud Aldenhoven

Sep 1 '06 #1
18 1790
jwaixs schrieb:
Hello,

How can I disgrate (probably not a good word for it) a list? For
example:

a = [1,2]
b = 3
c = [a] + [b] # which makes [[1,2],3]
Why do you wrap a in a list? Just

c = a + [b]

will do it.

Diez
Sep 1 '06 #2

Diez B. Roggisch wrote:
Why do you wrap a in a list? Just

c = a + [b]

will do it.
Yes I know, but the problem is I don't know if 'a' is a list or not. I
could make a type check, but I don't want to program in that way.

Noud

Sep 1 '06 #3
jwaixs wrote:
Hello,

How can I disgrate (probably not a good word for it) a list? For
example:

a = [1,2]
b = 3
c = [a] + [b] # which makes [[1,2],3]

Then how can I change c ([[1,2],3]) into [1,2,3]? I have a simple
function for this:
=============== =========
def flatten(l):
r = []
s = [l]
while len(s) 0:
i = s.pop()
if i.__class__ == list:
for c in i:
s.append(c)
else:
r.append(i)
return r
=============== =========
But this function isn't really doing it in the "python-way". Doesn't
have python an obscure function or buildin to do this?
No, it doesn't, but it's easy to roll one on your own, e.g. using a
recursive generator; in fact, if you had searched for "flatten" in the
google group of c.l.py, you'd find this: http://tinyurl.com/ndobk
George

Sep 1 '06 #4
jwaixs wrote:
Hello,

How can I disgrate (probably not a good word for it) a list? For
example:

a = [1,2]
b = 3
c = [a] + [b] # which makes [[1,2],3]

Then how can I change c ([[1,2],3]) into [1,2,3]? I have a simple
function for this:
=============== =========
def flatten(l):
r = []
s = [l]
while len(s) 0:
i = s.pop()
if i.__class__ == list:
for c in i:
s.append(c)
else:
r.append(i)
return r
=============== =========
But this function isn't really doing it in the "python-way". Doesn't
have python an obscure function or buildin to do this?
I'm not sure what makes it against "the python-way"...I would
likely just use a "for" loop structure rather than a while loop.
I would also skip copying the parameter and popping its
elements off. Lastly, I would use a slightly broader test than
asking if the item is a list (to handle sub-classes, sets,
dictionaries, etc):
>>def flatten(x):
.... q = []
.... for v in x:
.... if hasattr(v, '__iter__'):
.... q.extend(flatte n(v))
.... else:
.... q.append(v)
.... return q
....
>>flatten([1,2,3])
[1, 2, 3]
>>flatten([1,2,3, [5,6]])
[1, 2, 3, 5, 6]
>>flatten([1,2,3, [5,6, [7,8]]])
[1, 2, 3, 5, 6, 7, 8]
>>flatten([1,2,3, [5, {1:3,5:1},6, set([7,8])]])
[1, 2, 3, 5, 1, 5, 6, 8, 7]

I'm not sure if '__iter__' is the right thing to be looking for,
but it seems to work at least for lists, sets, dictionarys (via
their keys), etc. I would use it because at least then you know
you can iterate over it

I don't know of any builtin that will go to arbitrary depths, and
haven't figured out a clean way to do this with any sort of
list-comprehension, reduce/map call, or anything of the like.
The ability to flatten requires recursing down nested data
structures...re cursion is something that list comprehensions,
map()/reduce() commands, etc. aren't so good as (at least as far
as I've learned).

-tkc



Sep 1 '06 #5
jwaixs wrote:
>
Diez B. Roggisch wrote:
>Why do you wrap a in a list? Just

c = a + [b]

will do it.

Yes I know, but the problem is I don't know if 'a' is a list or not. I
could make a type check, but I don't want to program in that way.
Somewhere in the call chain you have made the decision "I want this function
to accept both lists and scalars", but always passing in lists is probably
the better approach. If you want to go with your original idea -- googling
in c.l.py will turn up many more or less optimized variants of flatten()
that basically follow the same approach as yours. There is also
Tkinter._flatte n() which you can use though it gives you a tuple, not a
list -- the place at least should meet the "obscurity" criterion :-)

Peter
Sep 1 '06 #6
Tim Chase wrote:
>>def flatten(x):
... q = []
... for v in x:
... if hasattr(v, '__iter__'):
... q.extend(flatte n(v))
... else:
... q.append(v)
... return q
...
Let's do some nitpicking on "pythonic" style. A more pythonic way to do
it would be:

try:
q.extend(v)
except TypeError:
q.append(v)

Sep 1 '06 #7

Tim Chase wrote:
I'm not sure if '__iter__' is the right thing to be looking for,
but it seems to work at least for lists, sets, dictionarys (via
their keys), etc. I would use it because at least then you know
you can iterate over it
AFAIK and as seen throughout posts on c.l.py, the best way to check if
something is iterable is:

try:
iter(obj)
except TypeError:
<obj is not iterable>
else:
<obj is iterable>

- Tal

Sep 1 '06 #8
On 2006-09-01, jwaixs <jw****@gmail.c omwrote:
Hello,

How can I disgrate (probably not a good word for it) a list? For
example:

a = [1,2]
b = 3
c = [a] + [b] # which makes [[1,2],3]

Then how can I change c ([[1,2],3]) into [1,2,3]? I have a
simple function for this:
You might try:

c = a + [b]

instead, to avoid the issue.
But this function isn't really doing it in the "python-way".
Doesn't have python an obscure function or buildin to do this?
I don't know if the following is the Python way, but I think it's
cute:

def flatten(x):
"""Flatten list x, in place."""
i = 0
while i < len(x):
if isinstance(x[i], list):
x[i:i+1] = x[i]
i = i+1

--
Neil Cerutti
In my prime I could have handled Michael Jordan. Of course, he
would be only 12 years old. --Jerry Sloan
Sep 1 '06 #9
On 2006-09-01, Tal Einat <ta************ @gmail.comwrote :
Tim Chase wrote:
>I'm not sure if '__iter__' is the right thing to be looking
for, but it seems to work at least for lists, sets,
dictionarys (via their keys), etc. I would use it because at
least then you know you can iterate over it

AFAIK and as seen throughout posts on c.l.py, the best way to
check if something is iterable is:

try:
iter(obj)
except TypeError:
<obj is not iterable>
else:
<obj is iterable>
That confounds me. Of course, I'm coming from a C++, where you
never want to throw an exception in a common case, hence the name
'exception'. The Python FAQ does say that raising and catching an
exception is an expensive operation. I see that type-checking is
good to avoid, but type-checking must be better than "abusing"
exceptions in this way. Is the above really a popular idiom?

If so, I guess I'll get used to it.

--
Neil Cerutti
Sep 1 '06 #10

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

Similar topics

6
3075
by: massimo | last post by:
Hey, I wrote this program which should take the numbers entered and sort them out. It doesnąt matter what order, if decreasing or increasing. I guess I'm confused in the sorting part. Anyone has any advices?? #include <iostream> using namespace std;
10
15105
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy *enemydata; // Holds information about an enemy (in a game) // Its a double linked list node
24
5720
by: Robin Cole | last post by:
I'd like a code review if anyone has the time. The code implements a basic skip list library for generic use. I use the following header for debug macros: /* public.h - Public declarations and macros */ #ifndef PUBLIC #define PUBLIC
4
3588
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; };   struct pcb *pcb_pointer;
3
2698
by: chellappa | last post by:
hi this simple sorting , but it not running...please correect error for sorting using pointer or linked list sorting , i did value sorting in linkedlist please correct error #include<stdio.h> #include<stdlib.h> int main(void) {
0
1812
by: drewy2k12 | last post by:
Heres the story, I have to create a doubly linked list for class, and i have no clue on how to do it, i can barely create a single linked list. It has to have both a head and a tail pointer, and each node in the list must contain two pointers, one pointing forward and one pointing backwards. Each node in the list will contain 3 data values:...
10
6554
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
0
8613
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be anything from a short integer value to a complex struct type, also has a pointer to the next node in the single-linked list. That pointer will be NULL...
12
4008
by: kalyan | last post by:
Hi, I am using Linux + SysV Shared memory (sorry, but my question is all about offset + pointers and not about linux/IPC) and hence use offset's instead on pointers to store the linked list in the shared memory. I run fedora 9 and gcc 4.2. I am able to insert values in to the list, remove values from the list, but the problem is in...
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7413
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7751
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4943
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3440
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1874
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.