1

i can't understand the meaning of result = result[1:] + (elem,) in the script, why there is a , in the bracket and what is result[1:]? Thanks in advance

def window_1(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result
mark Lan
  • 51
  • 1
  • `(elem,)` is a tuple where as `(elem)` is same as `elem`. `(1,2,3) + (4,)` will give you a new tuple `(1,2,3,4)` – Epsi95 Sep 08 '21 at 11:23
  • 1
    `result[1:] + (elem,)` = Everything in `result` *excluding the first item* plus one new item. – deceze Sep 08 '21 at 11:25

1 Answers1

1

your type of result is a tuple, when you want create a tuple with one element you should write (elem,).

And in list index of list start from zero when you write [1:] you want get element of list from index one to end of list.

see this example:

result = tuple([1,2,3])
print(result[1:])
result + (4,)

Output:

(2, 3)
(1, 2, 3, 4)
I'mahdi
  • 11,310
  • 3
  • 17
  • 23