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

2

u/Broad_Revolution6591 4d ago

Thanks guys! I understand it now

9

u/jamesfowkes 4d 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)

4

u/Verronox 4d 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 4d ago

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

2

u/Verronox 4d 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 4d 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).

3

u/Lion2471 4d ago

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

2

u/Outside_Complaint755 4d ago

Thats unpacking.  The code is making the assumption that line will always split into exactly two pieces.  The first piece is assigned to name and the second piece is assigned to qty

2

u/Money_Ad_5277 4d ago

This is unpacking (or destruction if you are familiar to js), what you do is basically a short version of
name = line.strip().split(",")[0]
qty = line.strip().split(",")[1]
which will throw an error, if len(line.strip().split(",")) > 2

1

u/Atypicosaurus 3d ago

Try this

x, y, z = 1,2,3

Then print x and y and z.

You basically can assign values to variables on one line. Both lines are handled as tuples (x, y, z) = (1,2,3) and as long as the tuple sizes are the same, python will understand them as is.

A function also can return a tuple:

def foo():
return (1,2,3)

And you can assign the return values one by one like

x = foo()[0]

Or

x,y,z = foo()

This is what's happening in your case.

1

u/frnzprf 4d ago edited 4d 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

1

u/IWant2rideMyBike 4d ago

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

The variable line is a string. The strip() method of a string removes whitespace at the beginning and the end of a string and returns a new string. This string is split at commas, creating a list of strings. Then the list is unpacked (see https://www.geeksforgeeks.org/python/python-unpack-list/ ) into the two variables name and qty. If a line contains more than one comma this step will fail.

0

u/ninhaomah 4d ago

What is in one of those lines ?

Name,quantity ?

0

u/AlexMTBDude 4d ago

Try this and you'll get it:

line = "somename,someqty"
name, qty = line.strip().split(',')
print("name =", name)
print("qty =", qty)

0

u/zztopsboatswain 4d ago

Good question. I learned something from this thread too :)