বেশিরভাগ সময় প্রথম পুনরাবৃত্তিকে শেষের পরিবর্তে বিশেষ ক্ষেত্রে করা সহজ (এবং সস্তা) হয় :
first = True
for data in data_list:
if first:
first = False
else:
between_items()
item()
এটি যে কোনও পুনরাবৃত্তিযোগ্য এমনকি তাদের জন্যও কাজ করবে len()
:
file = open('/path/to/file')
for line in file:
process_line(line)
# No way of telling if this is the last line!
এগুলি ছাড়াও, আমি মনে করি না যে এটি করার চেষ্টা করছেন তার উপর নির্ভর করে একটি সাধারণতর উত্কৃষ্ট সমাধান রয়েছে। উদাহরণস্বরূপ, আপনি যদি একটি তালিকা থেকে স্ট্রিং তৈরি str.join()
করে থাকেন তবে for
"বিশেষ ক্ষেত্রে" একটি লুপ ব্যবহার না করে স্বাভাবিকভাবে ব্যবহার করা ভাল ।
একই নীতি ব্যবহার করে তবে আরও কমপ্যাক্ট:
for i, line in enumerate(data_list):
if i > 0:
between_items()
item()
দেখে মনে হচ্ছে, তাই না? :)
@ আফকো এবং অন্যদের জন্য যাঁদের সত্যিকারের ব্যতীত পুনরাবৃত্তের বর্তমান মানটি len()
সর্বশেষ হয় কিনা তা খুঁজে বের করতে আপনার পক্ষে সামনের দিকে তাকাতে হবে:
def lookahead(iterable):
"""Pass through all values from the given iterable, augmented by the
information if there are more values to come after the current one
(True), or if it is the last value (False).
"""
# Get an iterator and pull the first value.
it = iter(iterable)
last = next(it)
# Run the iterator to exhaustion (starting from the second value).
for val in it:
# Report the *previous* value (more to come).
yield last, True
last = val
# Report the last value.
yield last, False
তারপরে আপনি এটি ব্যবহার করতে পারেন:
>>> for i, has_more in lookahead(range(3)):
... print(i, has_more)
0 True
1 True
2 False