2

I have the following code structure in my Python script:

for fullName in lines[:-1]:
    do stuff ...

This processes every line except for the last one. The last line is a company name and all the rest are people's names. This works except in the case where there's no company name. In this case the loop doesn't get executed. There can only be one name if there's no company name. Is there a way to tell Python to execute this loop at least once?

Stephen Rasku
  • 2,554
  • 7
  • 29
  • 51

5 Answers5

2

You could do it like this, dynamically setting the end of your range based on the length of lines:

i = len(lines)
i = -1 if i > 1 else i
for fullName in lines[:i]:
    dostuff()
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
  • There were a lot of good suggestions for this post but this is the one I used. It was one of the first received and it works. – Stephen Rasku Jun 30 '13 at 14:09
  • Cheers, glad it helped you. If nothing else, the # of answers goes to show you how flexible Python is as a language! :) – Steven Moseley Jun 30 '13 at 21:51
2

How about using Python's conditional:

>>> name=['Roger']
>>> names=['Pete','Bob','Acme Corp']
>>> 
>>> tgt=name
>>> for n in tgt if len(tgt)==1 else tgt[:-1]:
...    print(n)
... 
Roger
>>> tgt=names
>>> for n in tgt if len(tgt)==1 else tgt[:-1]:
...    print(n)
... 
Pete
Bob
dawg
  • 98,345
  • 23
  • 131
  • 206
1

Use an if-statement:

if len(fullName) == 1: # Only one person
    dostuff_with_one_person() 
else:
    for fullName in lines[:-1]:
        dostuff()
TerryA
  • 58,805
  • 11
  • 114
  • 143
1

Straightforward method. Processing only till the last but one record, if there are more than one records.

for i in xrange(len(lines)):
   process lines[i]
   if i == len(lines)-2: break

If there is only one element, i will be 0 and that will be processed and i != -1. If There are more than one elements, lets say 2. After processing the first element, i will be 0 and i == (2-2) will be true and breaks out of the loop.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

This is essentially a do-while loop construct in Python.

Essentially, you can have a for loop or while loop with a break condition. For yours, you could do this:

def do_stuff(x):
    print(x)

for i,n in enumerate(lst):
    do_stuff(n)
    if i>=len(lst)-2:
        break
Community
  • 1
  • 1
the wolf
  • 34,510
  • 13
  • 53
  • 71