class Shopcart:
def __init__(self):
self.shoplist = []
def insert(self, item):
self.shoplist.append(item)
def showlist(self):
print(self.shoplist)
def remove(self, item):
item = input("what do you want to remove?")
for thing in shop list:
if item == thing:
self.shoplist.remove(objet)
shopcart = Shopcart()
shopcart.insert((input("What are you gonna buy?"))
shopcart.showlist()```
#๐ Help with classes and lists.
154 messages ยท Page 1 of 1 (latest)
@halcyon beacon
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
and?
Hmm why we inserting into shopcart
mind your indentations, they need to be correct
I'm doin it on phone
So it's kind of hard to see them
This is mostly what I could do from mind without syntax highlighting to see obvious errors, I want to get more into how classes, but specially lists work, because I just have basic understanding of these topics.
From what I see you have a extra space before everything
the init function is one space too far
I think
It might make more sense to show the user a selection of items they could possibly buy (either hard-coded or pulled from a file or database or something), validate that selection when they make one, then add it to their cart.
i see, but in python the code won't work if it's not correct
so they are essential to get right in python
Yeah, don't mind the indentation, I can't do it right on phone and don't have access to my PC for now. ๐ญ
Or is there a text editor for this on phone?
Discord just scrambles my text
Try pyroid ig
It's a python interpreter
Its in playstore
If you're fine with using the browser you could use a site like https://www.online-python.com/
Build and Run your Python code instantly. Online-Python is a quick and easy tool that helps you to build, compile, test your python programs.
Tyyy
I usually indent with tab on vs code so I'm kinda lost on my phone ๐ญ
what help do you need?
This
I want to know what else can I do with lists specifically, classes are something secondary for now
Oh, I had a typo, I put remove(object) instead of thing

Have you heard of and/or studied list comprehensions?
There are some indentation errors. self.shoplist.remove(objet) what is objet? I think you meant to remove item.
And in the remove function you dont have to insert the argument "item" if you define the variable "item" inside the function
So instead of remove(self, item), I can just put self?
classes and lists are two different things, kinda, lists allows you to dynamically store and remove data from it.
Classes, traditionally are a "template" for creating your custom data type. The data type can do different things. For example, list is also a class, an in built one.
I'd recommend you to explore both of these separately on your own and see how they work
Yeah, because in your case you're asking for item as an input only if you call the function
Ah, right
Then, let's get rid of classes and go on with lists since it's the simpler topic.
For example, if I have a list, I know I can put stuff in and out with append and remove
Sure, you can do this with just normal functions and list operations, you aren't really making use of OOP here tbf
I know there are different types of lists
dictionaries, tuples and sets, what's the difference?
Are you doing this project to learn about classes or learm about lists?
Kind of both, but we'll start with lists
Do you know how to filter elements out of that list easily? Say you want to find all items that start with a certain letter (assuming all items in the list are strings). Would you know how to do that?
Then I'll go on to classes
Mhmm
Let me see
I'd say the same thing. Start with lists first then move to classes
if we should nitpick here, list are a class, just like all data types in python
but i understand what you mean to say here in this context
Lets say I have a list with
["Apple", "Soda", "Water", "Milk", "Pineapple", "Almond Milk"]
and I want just the items that start with "A"?
Wasn't that something like .startswith("a")
those aren't different types of lists, they are completely different data types, different types of collections, but all of them being collections they share some traits with each other
Yeah you can use startswith or check at the 0th index
Unless the string is empty
Ok ok ok
ik but in for loop it would just pass
Yes, and you can create a new list of just those elements using a list comprehension:
some_lst = ["Apple", "Soda", "Water", "Milk", "Pineapple", "Almond Milk"]
print([item for item in some_lst if item.startswith("A")])
They are different types of data structures which are built in for you.
Each of them have their own ways of storing data, with their pros and cons, and you need to choose the best one depending on the scenario.
lists: It's a variable length data structure that allows you to add, remove, index through elements in it.
tuples: This is an immutable data structure, best for when you have some constant data that you don't want to change
dictionary: Stores data in a key-value format, you can assign a "key" which can be a string, integer, float, bool, etc (an immutable datatype) which will represent a value.
set: This is an unordered data type and only holds unique values. If you don't care about in which order your data is present or only want to keep track of unique data, it's the best
Yeah, I did mention lists are a class as example there lol
Oh, I was making it. It ended up being larger than yours.
things = ["Apple", "Soda", "Water", "Milk", "Pineapple", "Almond Milk"]
for item in things:
if item.startswith("A"):
things.remove(item)
print(things)
Is it right?
This does not work
!e
things = ["Apple", "Almond Milk"]
for item in things:
if item.startswith("A"):
things.remove(item)
print(things)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
['Almond Milk']
you shouldn't modify a collection that you are iterating through, that will just cause a lot of headache
Ok, ok, so let's set classes even farther away, I need to understand those too. :b
Which would be the best way to do this?
If you find yourself having to mutate a list in a loop, the best way to go about it would to have another list containing the elements you want or not (whichever you need), instead of mutating the original list
to create a new list and put everything in that you want to keep is one way, list comprehension more or less does that in one line
So I have to make a second list that's empty and append the items I want in that list?
Nope. Take a look at my code that uses a list comprehension again: #1483153472172855366 message
that or make a list comprehension that does more or less that without you needing to create the empty list first
things = ["Apple", "Soda", "Water", "Milk", "Pineapple", "Almond Milk"]
final = []
for item in things:
if item.startswith("A"):
final.append(item)
print(final)
you now you can run code here, right?
That looks way more confusing uhh
and if you're modifying the index while maintaining the same size, then it's fine to mutate
So you can put the functions inside [] and it'll be a list itself?
No what
I mean what he did
you can rewrite the for loop as a list comp yes
[items for item in somelist if item.startswith("A")]
it creates a list with what the code specified inside it?
they are calling the function inside the list comprehension, you can call a function anywhere, what matters is what the function is returning into the for loop of it
yes
and it should be [items for item in somelist if item.startswith("A")]
That's really useful, ty Peachteaenjoyer :3
Basically yeah, a new list. It's saying for every item in the existing list where if item.startswith("A") is true, give me all of those items in a new list
Ok, so
If I want to print a list, it's printed as the list itself, that's ugly
What if I want
Apple, Soda, Almond Milk, etc
you can assign the list comprehension to another variable and for loop over it again and print it however you want
No prob ๐
so
for items in somelist:
print(item)
Or use some useful string functions to do it for you
It will print every item in a new line, if that's what you want
And how do I make it a single line?
I can show you two ways
Let me see, let me see
print(*somelist, sep=", ")
Do you know about the end argument in the print function?
Or you could do that too
Would be better
Or if you wanna do with string method,
print(", ".join(somelist))
I saw it on the CS50 thing but I don't remember anymore
why the *?
!e
fruits = ["Apple", "Banana", "Orange"]
formatted = ", ".join(fruits)
print(formatted)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Apple, Banana, Orange
Unpacks the elements of the list so it doesn't have those quotes around all the strings
OHHHHHH
That's kinda cool
In formatted = ", ".join(fruits)
", " is the separator for all elements
And inisde the .join() you pass in an iterable data that you want to have the separator applied on
Oh wait, I have an idea
!e
fruits = ["Apple", "Banana", "Orange"]
print(", ".join(fruits))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Apple, Banana, Orange
OOHH IT WORKS
Indeed
I just put the extra variable to make it easier to read, you can still print it directly if you wish to
Then I chan change the separator to any str?
!e
fruits = ["Apple", "Banana", "Orange"]
formatted = "and ".join(fruits)
print(formatted)
Just remember that string is an immutable data type, none of the string methods mutate the data within it, it always returns a new string, so don't forget to either store the data in a new variable or print it out
Immutable and mutable is kind of confusing for me, but what I get is:
Immutable can't be changed after.
Mutable can?
Yes, you'll need to fix the formatting
!e
fruits = ["Apple", "Banana", "Orange"]
formatted = " and ".join(fruits)
print(formatted)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Apple and Banana and Orange
Niceeee
Mutable means the data can be changes "in place", i.e a new object isn't created while the data is being changed.
Immutable means the data cannot change "in place", if you want to make some changes to an immutable data, a new object is created.
I'll give an example
!e
fruits = ["apple"]
print(f"{id(fruits)=} | {fruits=}")
fruits.append("banana")
print(f"{id(fruits)=} | {fruits=}")
print()
fruit_string = "orange"
print(f"{id(fruit_string)=} | {fruit_string=}")
fruit_string += ", cherry"
print(f"{id(fruit_string)=} | {fruit_string=}")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | id(fruits)=140373599426688 | fruits=['apple']
002 | id(fruits)=140373599426688 | fruits=['apple', 'banana']
003 |
004 | id(fruit_string)=140373597628928 | fruit_string='orange'
005 | id(fruit_string)=140373597860784 | fruit_string='orange, cherry'
I used the id function which returns the object's memery address. For the list example at the top, when i mutated it, the memory address remains the same before and after it was mutated, as it's a mutable data type. No new object was created when it did so
But for a string, when i tried mutating it, an entirely new object was created when doing so, hence the memory address is different. String is an immutable data type
@halcyon beacon you understand?
uhhhh
Ohhhhhhhh
That's an incredibly cool explanation. Ty.
No problemo
I had to go wash the dishes and now I have some other chores to do, but I want to keep this conversation for when I come back, it's being really useful
Alright, I'll still be on for while
Came back asap.
Ok, ok, so now, what else can I do with lists outside of
append, remove, startswith?
!e - did you see that you could do it like this too?
fruits = ["Apple", "Banana", "Orange"]
print(*fruits, sep=" and ")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Apple and Banana and Orange
startswith is a string method, not list
Lists are mainly designed for adding and removing elements during runtime. That's about it
Oh, so what about dictionaries? The keys and values you mentioned
Oh, yes, Peach guy told me about this way too
!e
player_data = {
"name": "Saber",
"coins": 900,
"high_score": 10
}
print(player_data["name"])
print(player_data["coins"])
print(player_data["high_score"])
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | Saber
002 | 900
003 | 10
Over here, name is a key representing the value "Saber", coins representing 900 and high_score representing the value 10
You can access the values of the keys by this syntax: dict_name[key_name] which will return the value associated with the key_name
You can update, add and remove data from the dict in a similar way too
!e
player_data = {
"name": "Saber",
"coins": 900,
"high_score": 10
}
# Adding a new entry
player_data["current_score"] = 0
# Updating an existing entry
player_data["name"] = "Jiggly"
# Removing an entry
del player_data["coins"]
print(player_data)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
{'name': 'Jiggly', 'high_score': 10, 'current_score': 0}
Also the keys need to be of immutable data types only, such as integers, floats, strings, bools, tuples and such
frozenset is also fine to use and comes in handy sometimes
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.