r/PythonLearning • • 12d 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

9

u/jamesfowkes 12d ago

This is known as "unpacking". The .split() method returns a list of values. Python allows you to directly "unpack" that list into variables:

>>> name, qty = "Phone,1".split(",")
>>> name
'Phone'
>>> qty
'1'

So first item in the first variable, second in the second and so on.

Note that the number of list items *must* equal the number of variables or you'll get an error:

>>> name, qty = "Phone,1,ABC123".split(",")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> name, qty = "Phone".split(",")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 2, got 1)

3

u/Lion2471 12d ago

Just for completeness, this can be done with any iterable, not just a list.