jacobcan118
jacobcan118

Reputation: 9037

How to get element from iterator object?

can anyone try to explain to me how the following code work? As I understand, unpack is like a, b, i = [1,2,3] but how the following code work to get x? I have try to debug if I have x = iter(collections.deque([1,2,3,4,5], maxlen=1)) <_collections._deque_iterator object at 0x01239>

import collections
x, = iter(collections.deque([1,2,3,4,5], maxlen=1))

Upvotes: 1

Views: 78

Answers (2)

Monty
Monty

Reputation: 791

Your code above produces x=5 for me, not an iterator object.

Usually with an iterator object, (like a generator) use of the next() works

Here's a short example with the fibonacci sequence. Using the yield produces a generator object.

def iterative_fib(n):
    a,b = 0,1
    i=1
    while i<n:
        a, b = b, a+b
#         print(b)
        i+=1
    yield b

x = iterative_fib(50)
next(x)  # 12586269025

I'm not 100% sure specifically in your case, but try using next because next expects an iterator. If this doesn't work, then maybe produce a code example that replicates your issue.

Docs for next() : https://docs.python.org/3/library/functions.html#next

Edit: Seeing some other answers regarding unpacking lists, here are some other ways using *:

a = [1,2,3,4,5]
a,b,c,d,e = [1,2,3,4,5] # you already mentioned this one
a, *b = [1,2,3,4,5]  # a =[1], b=[2, 3, 4, 5]
a, *b, c, d = [1,2,3,4,5]  #a =[1], b=[2,3], c=[4], d=[5]
*a, b, c = [1,2,3,4,5] # a=[1,2,3], b=[4], c=[5]
#But this wont work:
a, *b, *c = [1,2,3,4,5]  # SyntaxError: two starred expressions in assignment

Upvotes: 0

user3064538
user3064538

Reputation:

Here's a simpler example

>>> x = [24]
>>> x
[24]
>>> x, = [24]
>>> x
24

>>> x, y = [24, 96]
>>> x
24
>>> y
96

It's equivalent to your example since if you do list(iter(collections.deque([1,2,3,4,5], maxlen=1))) it's just a list with one element, [5].

You're correct that this is doing unpacking. You could write it as (x,) so that it looks more like a tuple if just x, is confusing. The comma after x makes x refer to the first element of a tuple with one element.

Upvotes: 1

Related Questions