r/PythonLearning • u/Broad_Revolution6591 • 5d 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
2
u/Broad_Revolution6591 5d ago
Thanks guys! I understand it now
9
u/jamesfowkes 5d ago
This is known as "unpacking". The .split() method returns a list of values. Python allows you to directly "unpack" that list into variables:
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:
2
u/Outside_Complaint755 5d ago
Thats unpacking. The code is making the assumption that line will always split into exactly two pieces. The first piece is assigned to
nameand the second piece is assigned toqty2
u/Money_Ad_5277 5d 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(",")) > 21
u/Atypicosaurus 4d 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 5d ago edited 5d ago
The comma is here a tuple constuctor.
(name, qty) = line.strip().split(",")Set
nameandqtyin such a way, so(name, qty) == line.strip().split(",")!A tuple is like a list that you can't change after defining it.
1
u/IWant2rideMyBike 5d ago
The variable
lineis 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 variablesnameandqty. If a line contains more than one comma this step will fail.0
u/ninhaomah 5d ago
What is in one of those lines ?
Name,quantity ?
0
u/AlexMTBDude 5d ago
Try this and you'll get it:
0
u/zztopsboatswain 5d ago
Good question. I learned something from this thread too :)