Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A simple python doubt
#1
In the following function,
def fibonaci():
    first = 0
    last = 1
    while True:
        first, last = last, first + last
        yield first
I am having difficulty understanding the first statement inside the while loop:
first, last = last, first + last

What it does ?
How first, last gets the values after each iteration ?
Reply
#2
It is a tuple assignment, a way to assign several variables in one statement
>>> first, last = 5, 23
>>> first
5
>>> last
23
mohamedrabeek likes this post
Reply
#3
You can think of this as packing and unpacking.
first = 1
last = 2

temp = last, first + last  # Pack last and first + last into temporary tuple
print(temp)
first, last = temp  # Unpack temporary tuple into first and last
print(first, last)
Output:
(2, 3) 2 3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Doubt about conditionals in Python. Carmazum 6 1,636 Apr-01-2023, 12:01 AM
Last Post: Carmazum
  doubt about python tkinter and sqlite3 LONDER 2 2,175 Aug-14-2021, 08:48 AM
Last Post: ibreeden
  Python Doubt csrlima 5 2,626 Jan-23-2021, 12:23 AM
Last Post: csrlima
  Python Exercise Doubt azure 4 2,694 Apr-21-2020, 01:15 PM
Last Post: azure
  Doubt in Regex Lookaround fullstop 3 2,399 Feb-03-2020, 09:53 AM
Last Post: Gribouillis
  A doubt with 'in' and 'not in' operators with strings newbieAuggie2019 7 3,632 Oct-23-2019, 03:11 PM
Last Post: perfringo
  OpenCV - Doubt in a line. ArjunSingh 1 2,506 Jul-14-2019, 03:36 PM
Last Post: ThomasL
  doubt saipython 1 2,837 Aug-21-2017, 06:05 AM
Last Post: Larz60+
  Basic Doubt in code prateek3 6 4,929 Aug-19-2017, 01:05 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020