Python Forum

Full Version: explanation of code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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
Thanks. That's clears things up.