I know that maps
, range
, filters
etc. in python3
return iterables, and only calculate value when required. Suppose that there is a map M
. I want to print the i^th
element of M.
One way would be to iterate till i^th
value, and print it:
for _ in range(i):
next(M)
print(next(M))
The above takes O(i)
time, where I have to find the i^th
value.
Another way is to convert to a list, and print the i^th
value:
print(list(M)[i])
This however, takes O(n)
time and O(n)
space (where n
is the size of the list from which the map M
is created). However, this suits the so-called "Pythonic way of writing one-liners."
I was wondering if there is a syntactic sugar to minimise writing in the first way? (i.e., if there is a way which takes O(i)
time, no extra space, and is more suited to the "Pythonic way of writing".)
map
? becauserange
objects are indexable in O(1) time.range(1, 100)[-1]
returns 99maps
andfilters
basically, although I didn't know aboutrange
objects being indexable in O(1) time.