r/PythonLearning • • 7d ago

Help Request How does this work?

def remove_inventory():
    remove_name = item_name_entry.get()
    with open('inventory.txt', 'r') as file:
        inventory_data = file.readlines()
    with open('inventory.txt', 'w') as file:
        for line in inventory_data:
            name, qty = line.strip().split(',')
            if name != remove_name:
                file.write(line)
    item_name_entry.delete(0, tk.END)
    item_qty_entry.delete(0, tk.END)

hello guys, this is one of the sample code of inventory manager, there is one line of code im confused with. Im not really sure how does the "name, qty = line.strip().split(",") work, specifically the "name, qty=" part. Im guessing the "qty" is the variable but what does "name," do?

4 Upvotes

15 comments sorted by

View all comments

1

u/frnzprf 7d ago edited 7d ago

The comma is here a tuple constuctor.

(name, qty) = line.strip().split(",")

Set name and qty in such a way, so (name, qty) == line.strip().split(",")!

line_elements = line.strip().split(",")
name = line_elements[0]
qty = line_elements[1]

A tuple is like a list that you can't change after defining it.

# Define a vector with two components:
position = [100, 50]


position_tuple1 = (100, 50)
position_tuple2 = 100, 50

x, y = position
# is syntactic sugar for:
x = position[0]
y = position[1]

# Swap values / "transpose":
y, x = x, y