473,796 Members | 2,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Modifying values in a list

The following code:

numbers = [1, 2, 3]
for value in numbers:
value *= 2
print numbers

results in the following output:
[1, 2, 3]

The intent of the code was to produce this output:
[2, 4, 6]

What is the reason for the output produced?
What code should be used to obtain the desired output?

Dec 29 '05 #1
4 1316
tr*********@ver izon.net writes:
The following code:

numbers = [1, 2, 3]
for value in numbers:
value *= 2
print numbers

results in the following output:
[1, 2, 3]

The intent of the code was to produce this output:
[2, 4, 6]

What is the reason for the output produced?
What code should be used to obtain the desired output?


How about this?

numbers = [1, 2, 3]
print [x * 2 for x in numbers]

--
Björn Lindström <bk**@stp.lingf il.uu.se>
Student of computational linguistics, Uppsala University, Sweden
Dec 29 '05 #2
tr*********@ver izon.net said unto the world upon 29/12/05 10:43 AM:
The following code:

numbers = [1, 2, 3]
for value in numbers:
value *= 2
print numbers

results in the following output:
[1, 2, 3]

The intent of the code was to produce this output:
[2, 4, 6]

What is the reason for the output produced?
What code should be used to obtain the desired output?


value is bound in the for loop, but none of that affects the list to
which numbers is bound.

One way:

IDLE 1.1.2
numbers = [1, 2, 3]
numbers = [x * 2 for x in numbers]
print numbers [2, 4, 6]


HTH,

Brian vdB
Dec 29 '05 #3
On Thu, 2005-12-29 at 11:43, tr*********@ver izon.net wrote:
The following code:

numbers = [1, 2, 3]
for value in numbers:
value *= 2
print numbers

results in the following output:
[1, 2, 3]

The intent of the code was to produce this output:
[2, 4, 6]

What is the reason for the output produced?
What code should be used to obtain the desired output?


1) Read http://www.effbot.org/zone/python-objects.htm and reread it
until you understand why your code doesn't work.

2) Use a list comprehension:
numbers = [ value*2 for value in numbers ]

-Carsten
Dec 29 '05 #4
As others have already posted, changing the value of 'value' has
nothing to do with the list variable 'numbers'. To modify the list in
place, you need to access its members by index. The following code
does this:

numbers = [1,2,3]
for i in range(len(numbe rs)):
numbers[i] *= 2
print numbers

But this is how a C or Java programmer would approach this task, and is
not very Pythonic.

A bit better is to use enumerate (avoids the ugly range(len(blah) )
looping):

numbers = [1,2,3]
for i,val in enumerate(numbe rs):
numbers[i] = val*2

This also modifies the list in place, so that if you are modifying a
very long (and I mean really quite long - long enough to question why
you are doing this in the first place) list, then this approach avoids
making two lists, one with the old value and one with the new.

But the most Pythonic is to use one of the list comprehension forms
already posted, such as:

numbers = [ x*2 for x in numbers ]

-- Paul

Dec 29 '05 #5

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

Similar topics

4
2988
by: dustin.getz | last post by:
consider the following working loop where Packet is a subclass of list, with Packet.insert(index, iterable) inserting each item in iterable into Packet at consecutive indexes starting at index. i=0 while(i<len(packet)-4): if packet==Packet("01110"): packet.insert(i, "01111") i+=10 #skip the 5 bits inserted, and skip the 5 bits just checked bc overlap should not trigger insertion
5
2641
by: IUnknown | last post by:
Ok, we are all aware of the situation where modifying the folder structure (adding files, folders, deleting files, etc) will result in ASP.NET triggering a recompilation/restart of the application. In a nutshell, I understand how this can be considered desireable by some, but I am not one of those people. My situation is that we have a root site (hosted @ http://www.mydomain.com) in the root application folder '/'.
6
1787
by: John [H2O] | last post by:
I would like to write a function to write variables to a file and modify a few 'counters'. This is to replace multiple instances of identical code in a module I am writing. This is my approach: def write_vars(D): """ pass D=locals() to this function... """ for key in D.keys(): exec("%s = %s" % (key,D))
2
4406
by: ismailc | last post by:
Good day, I need help. I would like to Update a Sharepoint List (Document Library) Folders using Web Services with Javascript. I have searched on Goggle but nothing that updates a document Library using UpdateListsItem method & with it being a clientside i need to pass NT Credentials to the List Please provide code as I have to get this going & have no clue. Please Assist
0
9680
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10455
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10173
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9052
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7547
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6788
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.