Access last element after iteration

Frank Millman frank at chagford.com
Tue Jul 7 08:26:25 EDT 2020


Hi all

After iterating over a sequence, the final element is still accessible. 
In this case, the variable 'i' still references the integer 4.

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>>
 >>> for i in range(5):
...     print(i)
...
0
1
2
3
4
 >>> print(i)
4
 >>>

Is this guaranteed in Python, or should it not be relied on?

If the latter, and you wanted to do something additional using the last 
element, I assume that this would be the way to do it -

 >>> for i in range(5):
...     print(i)
...     j = i
...
0
1
2
3
4
 >>> print(j)
4
 >>>

Alternatively, this also works, but is this one guaranteed?

 >>> for i in range(5):
...     print(i)
... else:
...     print()
...     print(i)
...
0
1
2
3
4

4
 >>>

Frank Millman



More information about the Python-list mailing list