Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
explanation of code
#1
The below snippets were taken from the website for xlswriter. I don't understand what the
first snippet is doing (the part that starts with expenses = (. Is that a function? I'm completely new to Python (as is probably obvious lol).

# Some data we want to write to the worksheet.
expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# Iterate over the data and write it out row by row.
for item, cost in (expenses):
    worksheet.write(row, col, item)
    worksheet.write(row, col + 1, cost)
    row += 1
Reply
#2
A group of items in the brackets [] separated by commas is a list. The parentheses don't denote a function, in this case they denote a tuple. So this is a tuple of lists.

In Python, for loops can have multiple variables where you expect the counter - hence the for item, cost in (expenses). That pulls the two pieces of data and labels them item and cost out of each record in our tuple, expenses. You then write those values into the first two columns of the worksheet.

More on lists, tuples, dictionaries, and other data structures can be found here
Reply
#3
Thanks. That's clears things up.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Explanation of code ejKDE 4 372 Feb-26-2024, 02:50 PM
Last Post: ejKDE
  A better explanation of the last post Led_Zeppelin 9 2,374 Sep-20-2022, 05:08 PM
Last Post: deanhystad
  Operator meaning explanation Sherine 3 2,023 Jul-31-2021, 11:05 AM
Last Post: Sherine
  Explanation of except ... as : Fernando_7obink 2 1,922 Feb-13-2021, 04:45 AM
Last Post: deanhystad
  .maketrans() - a piece of code which needs some explanation InputOutput007 5 2,955 Jan-28-2021, 05:05 PM
Last Post: buran
  .remove() from a list - request for explanation InputOutput007 3 2,214 Jan-28-2021, 04:21 PM
Last Post: InputOutput007
  Explanation of the left side of this statement please rascalsailor 3 2,494 Sep-09-2020, 02:02 PM
Last Post: rascalsailor
  Need explanation of one line of code Fliberty 6 3,472 Feb-18-2020, 12:50 AM
Last Post: Fliberty
  While loop explanation rdgbl 1 2,300 Dec-18-2018, 01:03 AM
Last Post: stullis
  Lamda function explanation mrcool4 4 3,546 Jul-04-2018, 10:44 AM
Last Post: mrcool4

Forum Jump:

User Panel Messages

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