1

I defined a simple function to return the first item in an iterable, or an error:

def first(iterable):
    iterator = iter(iterable)
    try:
        return next(iterator)
    except StopIteration:
        raise ValueError("iterable is empty")

In the shell, this function does what you'd expect:

>>> first({"1st", "2nd", "3rd"})
'1st'
>>> first({"1st", "2nd", "3rd"})
'1st'
>>> first(["1st", "2nd", "3rd"])
'1st'

However, in Jupyter Notebook, it returns the second element in a set, but the first element in a list.

first({"1st", "2nd", "3rd"})
'2nd'

first(["1st", "2nd", "3rd"])
'1st'

first(set(["1st", "2nd", "3rd"]))
'2nd'

I'm using Python 3.6.5 in Anaconda in both cases.

Am I mising something obvious?

Evan
  • 2,121
  • 14
  • 27
  • 1
    Sets have no defined order, is why. – Martijn Pieters Jun 16 '18 at 17:52
  • 1
    Put differently: restart Jupyter, or run the same code again in any new Python interpreter. For string values, a random hash seed is used to prevent certain denial of service attacks. – Martijn Pieters Jun 16 '18 at 17:54
  • Restarting Jupyter (kernel) didn't change the output. I'll check out your linked question, thanks; I didn't get to that LOD when searching to see if this question had been asked previously. – Evan Jun 16 '18 at 18:02
  • 1
    You only have 3 elements in the set, so there isn't much scope to see the difference that often. – Martijn Pieters Jun 16 '18 at 18:06
  • 1
    Note that nothing in your question has anything to do with `iter()`. You could just paste `{"1st", "2nd", "3rd"}` into the terminal and see what order they are returned in. Run `python3 -c 'print({"1st", "2nd", "3rd"})'` a couple of times to see what happens. Jupyter is *not special here*. – Martijn Pieters Jun 16 '18 at 18:07
  • Understood, thanks for the explanations. – Evan Jun 16 '18 at 20:04

0 Answers0