473,698 Members | 2,556 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

alter / modify a list as well as iterate on its items / objects

Hello,

Can anyone point me towards an article or explain
how to properly alter a list as well as iterate
on its items? For example:

input:

word = ["albert", "likes", "surfing!"]

for word in sentence:
word += "foo"

result:

word = ["albertfoo" , "likesfoo", "surfingfoo "]

Thanks,
Derek Basch



_______________ _______________ ____
Do you Yahoo!?
Friends. Fun. Try the all-new Yahoo! Messenger.
http://messenger.yahoo.com/

Jul 18 '05 #1
4 2468
On Tue, 25 May 2004 12:57:32 -0700, Derek Basch wrote:
Hello,

Can anyone point me towards an article or explain
how to properly alter a list as well as iterate
on its items? For example:

input:

word = ["albert", "likes", "surfing!"]

for word in sentence:
word += "foo"

result:

word = ["albertfoo" , "likesfoo", "surfingfoo "]


word = ["albert","likes ","surfing! "]

you could do it with a map:

word = map(lambda x: x + "foo", words)

or with a list comprehension:

word = [x + "foo" for x in words]
Jul 18 '05 #2
Most of the time this is done without
a loop at all as follows:

word = ["albert", "likes", "surfing!"]

word = [x+"foo" for x in word]

word = [""albertfoo ", "likesfoo", "surfing!fo o"]

Much of what you use loops for in other
languages you don't need in Python. List
comprehensions is a very powerful tool and it is
worth spending some time learning about.

Some tutorial links:

http://www.secnetix.de/~olli/Python/...rehensions.haw

http://www.cosc.canterbury.ac.nz/~greg/python/listcomp/
Larry Bates
Syscon, Inc.

"Derek Basch" <db****@yahoo.c om> wrote in message
news:ma******** *************** **************@ python.org...
Hello,

Can anyone point me towards an article or explain
how to properly alter a list as well as iterate
on its items? For example:

input:

word = ["albert", "likes", "surfing!"]

for word in sentence:
word += "foo"

result:

word = ["albertfoo" , "likesfoo", "surfingfoo "]

Thanks,
Derek Basch



_______________ _______________ ____
Do you Yahoo!?
Friends. Fun. Try the all-new Yahoo! Messenger.
http://messenger.yahoo.com/

Jul 18 '05 #3
Derek Basch <db****@yahoo.c om> wrote in message news:<ma******* *************** *************** @python.org>...
Hello,

Can anyone point me towards an article or explain
how to properly alter a list as well as iterate
on its items? For example:

input:

word = ["albert", "likes", "surfing!"]

for word in sentence:
word += "foo"

result:

word = ["albertfoo" , "likesfoo", "surfingfoo "]

Thanks,
Derek Basch

..
..
..

An solution No. 992345739219242 .... is:-):
from operator import add
word = ["albert", "likes", "surfing!"]
map(add,word,['foo']*len(word)) ['albertfoo', 'likesfoo', 'surfing!foo']


Regards
Peter
Jul 18 '05 #4
Derek Basch wrote:
Can anyone point me towards an article or explain
how to properly alter a list as well as iterate
on its items? For example:

input:

word = ["albert", "likes", "surfing!"]

for word in sentence:
word += "foo"

result:

word = ["albertfoo" , "likesfoo", "surfingfoo "]


Note that the solutions presented so far do *not* modify the list in place.
This is important if you keep references to the list elswhere. For example:
backup = sample = ["alpha", "beta", "gamma"]
sample = map(lambda x: x + ".suffix", sample)
sample is backup False sample = [x + ".suffix" for x in sample]
sample is backup False

Here are two ways to achieve inplace modification:
backup = sample = ["alpha", "beta", "gamma"]
for i, x in enumerate(sampl e): .... sample[i] = x + ".suffix"
.... sample is backup True
backup = sample = ["alpha", "beta", "gamma"]
sample[:] = [x + ".suffix" for x in sample]
sample is backup True


Here the [:] slice on the left makes the difference.

Peter
Jul 18 '05 #5

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

Similar topics

9
2548
by: Jess Austin | last post by:
hi, I like the way that Python does lists, and I love the way it does iterators. But I've decided I don't like what it does with iterators of lists. Lists are supposed to be mutable sequences, but try to use an iterator of a list that you're mutating and watch it all fall to pieces. That is, if you change the length of a section of the list through which the iterator has already passed, it will lose track of where it is. I think...
3
2113
by: Thorsten Kampe | last post by:
I found out that I am rarely using tuples and almost always lists because of the more flexible usability of lists (methods, etc.) To my knowledge, the only fundamental difference between tuples and lists is that tuples are immutable, so if this is correct, than list are a superset of tuples, meaning lists can do everything tuples can do and more. Is there any advantage for using tuples? Are they "faster"? Consume less memory? When is...
8
2158
by: Sorin Sandu | last post by:
Is it posible to modify the lenghth of an array ? I want to do something like int i = 0; string debit = new string; string credit = new string; while (myread3.Read())
2
8792
by: Bob | last post by:
Hi, I have a list of widgets. I want to iterate through the selected items collection and modify one of the widgets properties. I tried foreach(widget w in lst.SelectedItems) w.MyProperty = something; but I get a message saying "Cannot modify members of w because it is a foreach iteration variable" What is the point of iteration if you can't modify the objects?
10
6764
by: pamelafluente | last post by:
Hi I have a sorted list with several thousands items. In my case, but this is not important, objects are stored only in Keys, Values are all Nothing. Several of the stored objects (might be a large number) have to be removed (say when ToBeRemoved = true). class SomeObj ToBeRemoved be a boolean field end class
15
3094
by: Macca | last post by:
Hi, My app needs to potentially store a large number of custom objects and be able to iterate through them quickly. I was wondering which data structure would be the most efficient to do this,a hashtable or a generic list. Is using enumerators to iterate through the data structure a good idea? I'd appreciate any suggesstions or advice,
1
6332
by: Danny Liberty | last post by:
I need some opionions on an issue here... Suppose I want to keep a collection of objects, each need to be uniquely identified by a number. This number has no meaning as long as it's unique, so it should be automatically generated for each new object. One more requirement is keeping the objects in the order in which they were inserted, not sorted by their ID. Considering the following options of implementation, which would be the best...
4
2981
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
4
2816
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
0
8683
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
9170
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
8901
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
7739
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
6528
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
4371
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.