473,745 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Last iteration?

Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9
Can this be acomplished somehow?

Thanks,

Florian
Oct 12 '07 #1
23 18074
Florian Lindner wrote:
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9
Can this be acomplished somehow?
You could do this:

l = [1,2,3]
s = len(l) - 1
for i, item in enumerate(l): # Py 2.4
if i == s:
print item*item
else:
print item

Or, you could look one step ahead:

l = [1,2,3]
next = l[0]
for item in l[1:]:
print next
next = item
print next * next

Stefan
Oct 12 '07 #2
Florian Lindner wrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9
Can this be acomplished somehow?
def last_iter(itera ble):
it = iter(iterable)
buffer = [it.next()]
for i in it:
buffer.append(i )
old, buffer = buffer[0], buffer[1:]
yield False, old
yield True, buffer[0]

for last, i in last_iter(xrang e(4)):
if last:
print i*i
else:
print i

Diez
Oct 12 '07 #3
On Oct 12, 11:58 am, Florian Lindner <Florian.Lind.. .@xgm.dewrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i
Yes, either use enumerate or just stop the loop early and deal with
the last element outside the loop.

xs = [1, 2, 3]
for x in xs[:-1]:
print x
print xs[-1] * xs[-1]

--
Paul Hankin

Oct 12 '07 #4
On Oct 12, 11:58 am, Florian Lindner <Florian.Lind.. .@xgm.dewrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9

Can this be acomplished somehow?
Another suggestion:

l = [1, 2, 3]
for i in l[:-1]: print i
i = l[-1]
print i*i
James

Oct 12 '07 #5
On Fri, 2007-10-12 at 12:58 +0200, Florian Lindner wrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9
Here's another solution:

mylist = [1,2,3]
for j,i in reversed(list(e numerate(revers ed(mylist)))):
if j==0:
print i*i
else:
print i

;)

--
Carsten Haese
http://informixdb.sourceforge.net
Oct 12 '07 #6
On Oct 12, 2:18 pm, Carsten Haese <cars...@uniqsy s.comwrote:
On Fri, 2007-10-12 at 12:58 +0200, Florian Lindner wrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?
Example:
for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i
that would print
1
2
9

Here's another solution:

mylist = [1,2,3]
for j,i in reversed(list(e numerate(revers ed(mylist)))):
if j==0:
print i*i
else:
print i
Nice! A more 'readable' version is:

mylist = [1,2,3]
for not_last, i in reversed(list(e numerate(revers ed(mylist)))):
if not_last:
print i
else:
print i * i

--
Paul Hankin

Oct 12 '07 #7
Diez B. Roggisch wrote:
Florian Lindner wrote:
>can I determine somehow if the iteration on a list of values is the
last iteration?
def last_iter(itera ble):
it = iter(iterable)
buffer = [it.next()]
for i in it:
buffer.append(i )
old, buffer = buffer[0], buffer[1:]
yield False, old
yield True, buffer[0]
This can be simplified a bit since you never have to remember more than on
item:
>>def mark_last(items ):
.... items = iter(items)
.... last = items.next()
.... for item in items:
.... yield False, last
.... last = item
.... yield True, last
....
>>list(mark_las t([]))
[]
>>list(mark_las t([1]))
[(True, 1)]
>>list(mark_las t([1,2]))
[(False, 1), (True, 2)]

Peter
Oct 12 '07 #8
On Oct 12, 12:58 pm, Florian Lindner <Florian.Lind.. .@xgm.dewrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9

Can this be acomplished somehow?

Thanks,

Florian

If you want to do this over a list or a string, I'd just do:

for element in iterable[:-1]: print iterable
print iterable[-1] * iterable[-1]

No need for it to get more advanced than that :)

Oct 13 '07 #9
On Oct 12, 5:58 am, Florian Lindner <Florian.Lind.. .@xgm.dewrote:
Hello,
can I determine somehow if the iteration on a list of values is the last
iteration?

Example:

for i in [1, 2, 3]:
if last_iteration:
print i*i
else:
print i

that would print

1
2
9

Can this be acomplished somehow?

Thanks,

Florian
Maybe it's a leftover from my C++ days, but I find the iteration-based
solutions the most appealing. This is a refinement of the previous
post by Diez Roggisch. The test method seems to match your desired
idiom pretty closely:

def signal_last(lst ):
last2 = None
it = iter(lst)
try:
last = it.next()
except StopIteration:
last = None
for last2 in it:
yield False, last
last = last2
yield True, last

def test(t):
for isLast, item in signal_last(t):
if isLast:
print "...and the last item is", item
else:
print item

test("ABC")
test([])
test([1,2,3])

Prints:

A
B
....and the last item is C
....and the last item is None
1
2
....and the last item is 3

-- Paul

Oct 14 '07 #10

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

Similar topics

35
3741
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ------------------------------------------------------------- PEP: 323
2
2079
by: Abdullah Khaidar | last post by:
Is there any iteration style we must use to get faster processing time? I've tried with some style to concat number in list. But I still don't know which one is the recommended style. >>> def useListIteration(): list = result = "" for item in list: result += item return result
32
4151
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
0
1736
by: bunty.gopal | last post by:
I am trying to use the PreparedStatement's addBatch to load data in an ETL-like process into a table. There is a single prepared statement. The parameters are set on it and prepStmt.addBatch() is called. Then the next iteration of setting the params and adding to batch begins. Finally after setting the batch of 2 to 2000 rows, the prepStmt.executeBatch() is called. If the last row contains a null value for a particular DECIMAL field,...
75
5626
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
5
3965
by: Denis Petronenko | last post by:
Hello, for(int i=0; i<100; ++i){ cout << i << ","; } // how can i remove last comma here? ...... cout << endl;
0
2536
by: danikdanik | last post by:
Hello all, The folowing code below returns the same last access time of the tty i am writing to for every loop iteration, what just can't be true. What am I doing wrong? Is there any other way to get the last access time? anything faster,as I need to get the info many times ? btw, what is the difference between last access time and last modifiaction time of a file? my $curr_tty = `tty`; chomp($curr_tty); my $i = 1; while (1) { ...
1
5161
by: bunty.gopal | last post by:
This is the solution to the issue in the subject, question itself was posted in a previous thread long back. Use the latest DB2 db2cc.jar fixpack on the client, or add "deferPrepares=false" to the connection string when opening the connection (or connection pool properties, if deployed on a server like weblogic). The issue can be resolved using either of these options. Gopal
3
6899
by: Ilkka Maatta | last post by:
PHP code ..... <? //Open file. $file=fopen("file.txt","r"); //read file so long when it isn't end. while (!feof($file)) { //read and print row + LF. $rivi=fgets($file,1024);
0
8795
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9486
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...
0
9346
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9214
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8219
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
6763
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
6057
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();...
1
3287
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
2
2759
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.