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

assignment in a for loop

Hello everyone

Consider the following
l = [1,2]
for i in l: .... i = i + 1
.... l

[1, 2]

I understand (I think!) that this is due to the fact that in Python
what looks like "assignment" really is binding a name to an object. The
result is that inside the loop I am creating an object with value (i+1)
and then "pointing" the name i at it. Therefore, the object to which i
previously pointed (an element of list l) remains unchanged.

Two brief questions:

1) Is what I wrote above (minimally) correct?

2) Independently of the answer to 1, is there a way for me to assign to
elements of a list inside a loop and without resorting to C-style
ugliness of

for i in range(len(l))
l[i] = l[i] + 1

?

(Note: not using a list comprehension.)

Thanks in advance

Mack

May 17 '06 #1
6 1919
Sorry, my previous post probably was not very good at explaining _why_
I want to do this.

Suppose I want to do modify all arguments which are passed to a
function. Do I need to use a list comprehension such as

def f(arg1,arg2,arg3):

arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
...

This would be awful when, eg, one adds an argument to the function
definition. It would require edition of the code at two different
locations.

Thanks

Mack

MackS wrote:
Hello everyone

Consider the following
l = [1,2]
for i in l: ... i = i + 1
... l

[1, 2]

I understand (I think!) that this is due to the fact that in Python
what looks like "assignment" really is binding a name to an object. The
result is that inside the loop I am creating an object with value (i+1)
and then "pointing" the name i at it. Therefore, the object to which i
previously pointed (an element of list l) remains unchanged.

Two brief questions:

1) Is what I wrote above (minimally) correct?

2) Independently of the answer to 1, is there a way for me to assign to
elements of a list inside a loop and without resorting to C-style
ugliness of

for i in range(len(l))
l[i] = l[i] + 1

?

(Note: not using a list comprehension.)

Thanks in advance

Mack


May 17 '06 #2
"MackS" <ma***********@hotmail.com> writes:
l = [1,2]
for i in l: ... i = i + 1
... l
[1, 2]

I understand (I think!) that this is due to the fact that in Python
what looks like "assignment" really is binding a name to an
object. The result is that inside the loop I am creating an object
with value (i+1) and then "pointing" the name i at it. Therefore,
the object to which i previously pointed (an element of list l)
remains unchanged.


That's a fair explanation, yes.
Two brief questions:

1) Is what I wrote above (minimally) correct?
Correct for what? You can tell if it's *syntactically* correct by
simply running it.

As for any other "correct", define that. Does it do what you want it
to do?
2) Independently of the answer to 1, is there a way for me to assign
to elements of a list inside a loop and without resorting to C-style
ugliness of

for i in range(len(l))
l[i] = l[i] + 1
You can build a new list from your operations on the old one.

new_list = []
for x in old_list:
new_list.append(x+1)

You can also do it more succinctly with a list comprehension
expression.
(Note: not using a list comprehension.)


What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]

--
\ "Smoking cures weight problems. Eventually." -- Steven Wright |
`\ |
_o__) |
Ben Finney

May 17 '06 #3
"MackS" <ma***********@hotmail.com> writes:

[MackS, please don't top-post.]
Suppose I want to do modify all arguments which are passed to a
function. Do I need to use a list comprehension such as

def f(arg1,arg2,arg3):

arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
...

This would be awful when, eg, one adds an argument to the function
definition. It would require edition of the code at two different
locations.


If you anticipate increasing the number of values passed to the
function, and you're doing the same operation on all of them, why not
pass in a list::
def add_one_to_each(nums): ... """ Makes a new list with each value incremented by one. """
...
... incremented_nums = [x+1 for x in nums]
... return incremented_nums
... foo = [3, 5, 8]
bar = add_one_to_each(foo)
bar

[4, 6, 9]

--
\ "Some mornings, it's just not worth chewing through the leather |
`\ straps." -- Emo Philips |
_o__) |
Ben Finney

May 17 '06 #4
Thank you for your reply.

1) Is what I wrote above (minimally) correct?
Correct for what? You can tell if it's *syntactically* correct by
simply running it.

As for any other "correct", define that. Does it do what you want it
to do?


I was referring to my attempted explanation, not the code snippet.
[...]

What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]


Suppose I want to do anything as trivial as modify the values of the
list members _and_ print their new values. List comprehensions must not
contain statements, I think.
Mack

May 17 '06 #5
"MackS" <ma***********@hotmail.com> writes:
Thank you for your reply.


A pleasure to help.
What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]


Suppose I want to do anything as trivial as modify the values of the
list members _and_ print their new values. List comprehensions must
not contain statements, I think.


You're correct, but that's because you're creating a new list, not
modifying the existing one. The list comprehension can do anything you
like to generate each element, so long as it's an expression::
foo = [3, 5, 8]
print [x+1 for x in foo] [4, 6, 9] print [x**2 for x in foo] [9, 25, 64] print [str(x**2) for x in foo] ['9', '25', '64'] print [len(str(x**2)) for x in foo] [1, 2, 2]

If it's too complex to be readable in a single expression, make it a
function which returns a value, since calling a function is itself an
expression::
def get_result_of_complex_stuff(n): ... quad = n**4
... if len(str(quad)) % 2:
... word = "spam"
... else:
... word = "eggs"
... result = word.strip("s").title()
... return result
... foo = [3, 5, 8]
print [get_result_of_complex_stuff(x) for x in foo] ['Egg', 'Pam', 'Egg']

Once you have your new list being created by a list comprehension, do
what you like with it. If you want it to be stored, assigned back to
the original name, each value printed, or whatever you like, then do
so::
bar = [get_result_of_complex_stuff(x) for x in foo]
foo = bar
for x in foo:

... print x,
...
Egg Pam Egg

--
\ "One time a cop pulled me over for running a stop sign. He |
`\ said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__) don't believe everything I read.'" -- Steven Wright |
Ben Finney

May 17 '06 #6
MackS wrote:
(snip)
What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]
Suppose I want to do anything as trivial as modify the values of the
list members _and_ print their new values.


Then it's a sure design smell IMHO. Don't mix presentation with logic.
List comprehensions must not
contain statements, I think.


You're right.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 17 '06 #7

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

Similar topics

6
by: Sybren Stuvel | last post by:
Hi there, Is it possible to use an assignment in a while-loop? I'd like to do something like "loop while there is still something to be read, and if there is, put it in this variable". I've been...
10
by: ambar.shome | last post by:
Dear All, Whats the difference between a copy constructor and assignment operator. We can assign the values of member variables of one object to another object of same type using both of them....
77
by: berns | last post by:
Hi All, A coworker and I have been debating the 'correct' expectation of evaluation for the phrase a = b = c. Two different versions of GCC ended up compiling this as b = c; a = b and the other...
9
by: none | last post by:
Hi all, First, let me preface this by the fact that I'm completely new to the language, but not to programming in general. I'm trying to get my feet wet with something near and dear to my...
9
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by...
61
by: warint | last post by:
My lecturer gave us an assignment. He has a very "mature" way of teaching in that he doesn't care whether people show up, whether they do the assignments, or whether they copy other people's work....
9
by: Pete Bartonly | last post by:
Quick question, probably quite a simple matter. Take the follow start of a method: def review(filesNeedingReview): for item in filesNeedingReview: (tightestOwner, logMsg) = item if...
1
by: Gemmalouise1988 | last post by:
Hi everyone, My most important college assignment to date seems pretty basic on the outside but I'm sure this will interest a few of you. If you see this document:...
4
pdring
by: pdring | last post by:
Hi everybody, I have compleated an assignment in C for college and was very pleased with myself until I saw that extra marks could be obtained by modifiying the working program to meet a new...
7
by: isinc | last post by:
I have an assignment that I'm working on and am having trouble. Not too familiar with graphics. Any help/guidance would be much appreciated to see if what I have so far is okay and what I should do...
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: 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: 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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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.