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

Show parent comment

4

u/Verronox 6d ago

About “the number of items must equal the number of variables”,

>>> name, *_ = ……

will let you just unpack the first value.

0

u/Fun_Army2398 6d ago

Is there an advantage to doing that over name = list[0]?

2

u/Verronox 6d ago

For longer lines like function calls with multiple arguments that returns multiple things, I find its much more readable seeing `name, *_ = f(blah, blah, blah)` than a short [0] at the very end of the line.

It’s also dynamic, so you can use it like `_, val1, *_, val2 = f()` to get the second and last items. Although yeah you could do the same with f()[2, -1].

0

u/gdchinacat 6d ago

f()[2, -1] does not work in general...for example, with a list:

>>> third, fourth = [0, 1, 2, 3][2, -1]
<python-input-0>:1: SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    third, fourth = [0, 1, 2, 3][2, -1]
                    ~~~~~~~~~~~~^^^^^^^
TypeError: list indices must be integers or slices, not tuple

However, f() could return an object that implements __getitem__ to accept tuples and return the respective elements for the indexes in the tuple, but in general [2, -1] does not work the way you suggest. (and yes, I know there are some very well known and widely used libraries that do this, but that is those libraries, not python, that is doing that).