473,386 Members | 1,821 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,386 software developers and data experts.

Loop in list.

Jim
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.

Jul 18 '05 #1
19 4530
Jim wrote:
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.


Its called a list-comprehension. And as I don't know what books you mean, I
can't say if its covered there or not.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
Jim wrote:
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.

It's called a list comprehension and it appeared in Python 2.0.

http://www.amk.ca/python/2.0/index.h...00000000000000

Jeremy Jones
Jul 18 '05 #3
"Jim" <jt***@att.net> wrote:
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.


it's called "list comprehension", and was added in Python 2.0.

http://www.amk.ca/python/2.0/index.h...00000000000000
http://docs.python.org/tut/node7.htm...00000000000000
http://docs.python.org/ref/lists.html

Python 2.4 introduces a variation called "generator expressions":

http://www.python.org/doc/2.4/whatsnew/node4.html
http://www.python.org/peps/pep-0289.html
http://docs.python.org/ref/genexpr.html

</F>

Jul 18 '05 #4
Jim,

That is called a "list comprehension", and it is a feature which
appeared in python 2.3 (iirc). Thus if your books are about earlier
versions of python, list comprehensions will not be covered.

Check out the section of the tutorial about them at
http://docs.python.org/tut/node7.htm...00000000000000 .

Peace
Bill Mill
bill.mill at gmail.com
On Tue, 08 Feb 2005 06:50:08 -0800 (PST), Jim <jt***@att.net> wrote:
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.

--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #5
On Tue, 08 Feb 2005 06:50:31 -0800 (PST), Jim <jt***@att.net> wrote:
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.


It's called a "List Comprehension". There's a good historical reason
for the name, but you can be excused in not having looked under that
name in the index. See
<http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000>
for details.

They *should* be mentioned in most books, provided that it's vaguely
recent and covers Python 2.0 or later.

List comps have a cool new little sister, generator expressions - see
<http://www.brunningonline.net/simon/blog/archives/001025.html>.

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 18 '05 #6
Jim <jt***@att.net> wrote:
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.


It's a list comprehension. Unfortunately, this is a bad example of
one, since a much simplier way of writing the same thing would be:

mat = ['a'] * 3

After several years of them being in the language, I'm still somewhat
up in the air about the wisdom of list comprehensions. There is no
doubt that they're convenient and compact, but I think they make code
more difficult to read. The functional programming folks will
certainly disagree, and I realize I'm probably in the minority on
this, but that's my opinion.
Jul 18 '05 #7
Jim
Thanks for the help. Python is somewhat mysterious to an old fortan
programer.

Jim

Jul 18 '05 #8
Jim
Particularly one who can't spell. Fortran.

Jim

Jul 18 '05 #9
Jim

Someone on this list (SteveB) helped me quite a bit with a list
comprehension on a recent thread. Roy said it can be hard to read, and I
agree in part because I always thought they were hard to read, when in
actual fact I had just never bothered to learn properly. Here is a
mini-tutorial:

e.g. 1: The theory

'>>> a = [ <item1> for i in <item2> ]

item2 is iterable (like "range()" in your example)
item1 is the thing that is going to fill up the resulting list, and item1
is evaluated at each step of the "for" loop.

This is the same as
'>>> a = []
'>>> for i in <item2>:
'>>> a.append(<item1>)

e.g. 2: A real example

'>>> a = [i*2 for i in range(3)]
'>>> a
[0, 2, 4]

so "i*2" gets evaluated for each step in the "for" loop. The values of
"i" at each step are [0,1,2], according to how "range" works, so "i*2" is
what you end up with in the resulting list.

e.g. 3: They can be nested

'>>> a = [i*2*b for i in range(3) for b in range(4)]
'>>> a
[0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12]

Might take you a while to correlate the answer with the loop, but you
should be able to see after a while that this nesting is the same as

'>>> a = []
'>>> for b in range(4):
'>>> for i in range(3):
'>>> a.append(i*2*b)

keep well
Caleb
Jul 18 '05 #10
On Tue, 08 Feb 2005 23:07:09 -0500, Caleb Hattingh <ca****@telkomsa.net> wrote:
'>>> a = [i*2*b for i in range(3) for b in range(4)]
'>>> a
[0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12]

Might take you a while to correlate the answer with the loop, but you
should be able to see after a while that this nesting is the same as

'>>> a = []
'>>> for b in range(4):
'>>> for i in range(3):
'>>> a.append(i*2*b)


There is a subtle error in this explanation. The equivilence actually
looks like:

'> a = []
'> l1 = range(4)
'> l2 = range(3)
'> for b in l1:
'> for i in l2:
'> a.append(i*2*b)

Stephen
Jul 18 '05 #11
Jim a écrit :
Where did this type of structure come from:

mat = ['a' for i in range(3)] ?

This will produce a list of three elements but
I don't see reference for it in any of the books.

Now everyone told you *what* is it, I'll (very very dumbly) answer the
question : this syntax comes from Haskell.

HTH !-)
Bruno
Jul 18 '05 #12
Stephen

You're gonna have to help me here.....what is the effective difference?

Thanks
Caleb
'>>> a = []
'>>> for b in range(4):
'>>> for i in range(3):
'>>> a.append(i*2*b)


There is a subtle error in this explanation. The equivilence actually
looks like:

'> a = []
'> l1 = range(4)
'> l2 = range(3)
'> for b in l1:
'> for i in l2:
'> a.append(i*2*b)

Stephen


Jul 18 '05 #13
Stephen Thorne wrote:
'>>> a = [i*2*b for i in range(3) for b in range(4)]
'>>> a
[0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12]

Might take you a while to correlate the answer with the loop, but you
should be able to see after a while that this nesting is the same as

'>>> a = []
'>>> for b in range(4):
'>>> for i in range(3):
'>>> a.append(i*2*b)
There is a subtle error in this explanation.


if you run the example, you'll notice that it's not so subtle. read on.
The equivilence actually looks like:

'> a = []
'> l1 = range(4)
'> l2 = range(3)
'> for b in l1:
'> for i in l2:
'> a.append(i*2*b)


really?

def myrange(x):
print "RANGE", x
return range(x)

print [i*2*b for i in myrange(3) for b in myrange(4)]

a = []
for b in myrange(4):
for i in myrange(3):
a.append(i*2*b)
print a

a = []
l1 = myrange(4)
l2 = myrange(3)
for b in l1:
for i in l2:
a.append(i*2*b)
print a

prints

RANGE 3
RANGE 4
RANGE 4
RANGE 4
[0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12]
RANGE 4
RANGE 3
RANGE 3
RANGE 3
RANGE 3
[0, 0, 0, 0, 2, 4, 0, 4, 8, 0, 6, 12]
RANGE 4
RANGE 3
[0, 0, 0, 0, 2, 4, 0, 4, 8, 0, 6, 12]

(to translate a list comprehension to nested statements, remove
the result expression, insert colons and newlines between the for/if
statement parts, and put the append(result expression) part inside
the innermost statement)

</F>

Jul 18 '05 #14
Jim <jt***@att.net> wrote:
Thanks for the help. Python is somewhat mysterious to an old fortan
programer.


You might appreciate http://www.python.org/doc/Humor.html#habits
Jul 18 '05 #15
Hi Fredrik

*sigh* I think I will stop writing mini-tutorials :)

You are, of course, correct. And I really like your method of
explaining how to mentally juggle the LC into explicit loops.

I shudder to think how mnay people I confused with my incorrect
examples - I really should have tested them first.

Thanks again
Caleb
(to translate a list comprehension to nested statements, remove
the result expression, insert colons and newlines between the for/if
statement parts, and put the append(result expression) part inside
the innermost statement)

</F>


Jul 18 '05 #16
Jim
Wow! All I wanted to do was write the equivalence
of the Fortran statement: Real*4 matrix(n,n).

I'm going to have to go to the intrepreter to see what
your saying.

Thanks for all the help.

Jim

Jul 18 '05 #17
Jim wrote:
Wow! All I wanted to do was write the equivalence
of the Fortran statement: Real*4 matrix(n,n).


If you are doing numerical linear algebra in Python, you should use the
Numeric or Numarray modules. With Numeric, the equivalent is just

from Numeric import zeros
matrix = zeros([n,n],Float)

Jul 18 '05 #18
Jim
I did appreciate the reference. I started with Fortran
on an IBM (7040 maybe, not sure) using keypunched cards. Some of the
concepts of the newer languages take some to seem useable.

Jim

Jul 18 '05 #19
Jim
I assume this is one of the addons for Python. I know that there
is a great deal of stuff out there available for Python that does
some of the stuff that I am looking at, but I am interested in
learning to use Python. When I want to get faster and more
general, I will get some of this stuff or use a different language.

Thanks for the help.

Jim

Jul 18 '05 #20

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

Similar topics

33
by: Arthur | last post by:
>>>a= >>> for p in a: print p 1 2 3 >>> p 3 My naive expectation was that p would be 'not defined' from outside
0
by: Kingdom | last post by:
I Need some serious help here. strugling novis with ASP and javascript any help would be greatly appreciated The script below does exactly what I want it to do for each product on the two passes...
13
by: na1paj | last post by:
here's a simple linked list program. the DeleteNode function is producing an infinit loop i think, but i can't figure out where.. #include <stdio.h> typedef struct { char *str; //str is a...
5
by: Jani Yusef | last post by:
Based on an interview question I heard of but did not know the answer to....... How do you find and remove a loop from a singly linked list? In a google groups search I found the following code...
7
by: CodeRazor | last post by:
How is it possible to sort an array of ints using a for loop? I recently tried the suggestion a newsgroup user offered on how to perform this, but find that it doesn't work. He suggested the code...
5
by: Allerdyce.John | last post by:
Hi, I have this piece of code which loops thru a STL list, but that causs an infinite loop. bool Executer::group(MyList& bl, ResultList & grl) { for (ExecuterList::iterator i =...
10
by: sonu | last post by:
Hi All, here i have a daught how can i find wheather a linked list contains a loop or not.
1
by: Doug_J_W | last post by:
I have a Visual Basic (2005) project that contains around twenty embedded text files as resources. The text files contain two columns of real numbers that are separated by tab deliminator, and are...
8
by: malkarouri | last post by:
Hi everyone, I have an algorithm in which I need to use a loop over a queue on which I push values within the loop, sort of: while not(q.empty()): x = q.get() #process x to get zero or more...
0
by: Gary Herron | last post by:
Dan Upton wrote: Yes. Create a list of keys, and loop through it: pids = procs_dict.keys() for pid in pids: if procs_dict.poll() != None # do the counter updates del procs_dict Then the...
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$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.