Nutkin
Nutkin

Reputation: 111

Need help understanding python syntax

Can someone explain the syntax on lines 5 & 16

   1 # Using the generator pattern (an iterable)
   2 class firstn(object):
   3     def __init__(self, n):
   4         self.n = n
   5         self.num, self.nums = 0, []
   6 
   7     def __iter__(self):
   8         return self
   9 
  10     # Python 3 compatibility
  11     def __next__(self):
  12         return self.next()
  13 
  14     def next(self):
  15         if self.num < self.n:
  16             cur, self.num = self.num, self.num+1
  17             return cur
  18         else:
  19             raise StopIteration()
  20 
  21 sum_of_first_n = sum(firstn(1000000))

Upvotes: 1

Views: 105

Answers (2)

John Kugelman
John Kugelman

Reputation: 361710

self.num, self.nums = 0, []
cur, self.num = self.num, self.num+1

These are shorthands for the following:

self.num = 0
self.nums = []

and

cur = self.num
self.num = self.num + 1

As a personal preference, I would not use the compound assignments in either of these two lines. The assignments are not related, so there's no reason to combine them.

There are times when compound assignments can prove useful. Consider how one swaps two numbers in languages like C and Java:

temp = a
a = b
b = temp

In Python we can eliminate the temporary variable!

a, b = b, a

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122262

That's tuple assignment; you can assign to multiple targets.

The right-hand expression is evaluated first, and then each value in that sequence is assigned to the names on left-hand side one by one, from left to right.

Thus, self.num, self.nums = 0, [] assigns 0 to self.num and [] to self.nums.

See the assigment statements documentation:

  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Because the right-hand side portion is executed first, the line cur, self.num = self.num, self.num+1 assigns self.num to cur after calculating self.num + 1, which is assigned to self.num. If self.num was 5 before that line, then after that line cur is 5, and self.num is 6.

Upvotes: 3

Related Questions