Programming Practices for Readabililty
In general, if you feel like code is not self-describing, the usual solution is to factor it out into a well-named function:
def first(s):
'''Return the first element from an ordered collection
or an arbitrary element from an unordered collection.
Raise StopIteration if the collection is empty.
'''
return next(iter(s))
With that helper function, the subsequent code becomes very readable:
>>> extension = {'xml', 'html', 'css', 'php', 'xhmtl'}
>>> one_extension = first(extension)
Patterns for Extracting a Single Value from Collection
The usual ways to get an element from a set, dict, OrderedDict, generator, or other non-indexable collection are:
for value in some_collection:
break
and:
value = next(iter(some_collection))
The latter is nice because the next() function lets you specify a default value if collection is empty or you can choose to let it raise an exception. The next() function is also explicit that it is asking for the next item.
Alternative Approach
If you actually need indexing and slicing and other sequence behaviors (such as indexing multiple elements), it is a simple matter to convert to a list with list(some_collection)
or to use [itertools.islice()][2]
:
s = list(some_collection)
print(s[0], s[1])
s = list(islice(n, some_collection))
print(s)
iter
call too:next(iter(d.items()))
as.items
returns a View object. – Plumbernext(iter(ordered_dict.items()))
this will advance the iterator or not. As expected it does not advance the iterator! Also is it safe to assume thatnext(iter(ordered_dict.items()))
runs inO(1)
time? – Laboynext(iter(self.items()))
will give you the first pair(key, val)
– Premillenarian