#๐Ÿ”’ Help with classes and lists.

154 messages ยท Page 1 of 1 (latest)

halcyon beacon
#
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()```
last sandBOT
#

@halcyon beacon

Python help channel opened

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.

ionic prawn
#

and?

main cypress
#

Hmm why we inserting into shopcart

amber torrent
halcyon beacon
#

So it's kind of hard to see them

halcyon beacon
main cypress
#

From what I see you have a extra space before everything

shrewd bough
#

the init function is one space too far

main cypress
#

I think

sharp furnace
amber torrent
#

so they are essential to get right in python

halcyon beacon
#

Or is there a text editor for this on phone?

#

Discord just scrambles my text

main cypress
#

It's a python interpreter

#

Its in playstore

sharp furnace
halcyon beacon
#

I usually indent with tab on vs code so I'm kinda lost on my phone ๐Ÿ˜ญ

burnt rover
halcyon beacon
#

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

main cypress
sharp furnace
shrewd bough
#

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

halcyon beacon
burnt rover
shrewd bough
#

Yeah, because in your case you're asking for item as an input only if you call the function

halcyon beacon
#

For example, if I have a list, I know I can put stuff in and out with append and remove

burnt rover
halcyon beacon
shrewd bough
#

Are you doing this project to learn about classes or learm about lists?

halcyon beacon
sharp furnace
halcyon beacon
#

Then I'll go on to classes

shrewd bough
amber torrent
halcyon beacon
amber torrent
shrewd bough
proven sail
shrewd bough
sharp furnace
burnt rover
# halcyon beacon I know there are different types of lists dictionaries, tuples and sets, what's...

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

burnt rover
halcyon beacon
proven sail
#

!e

things = ["Apple", "Almond Milk"] 
for item in things:
    if item.startswith("A"):
        things.remove(item)
        
print(things)
last sandBOT
amber torrent
halcyon beacon
halcyon beacon
burnt rover
#

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

amber torrent
halcyon beacon
sharp furnace
amber torrent
halcyon beacon
#
things = ["Apple", "Soda", "Water", "Milk", "Pineapple", "Almond Milk"] 
final = []
for item in things:
    if item.startswith("A"):
        final.append(item)
        
        
print(final)
proven sail
#

You can also iterate in reverse

#

if just removing

amber torrent
halcyon beacon
proven sail
#

and if you're modifying the index while maintaining the same size, then it's fine to mutate

halcyon beacon
#

So you can put the functions inside [] and it'll be a list itself?

proven sail
#

No what

halcyon beacon
#

I mean what he did

proven sail
#

you can rewrite the for loop as a list comp yes

halcyon beacon
burnt rover
burnt rover
#

and it should be [items for item in somelist if item.startswith("A")]

halcyon beacon
#

That's really useful, ty Peachteaenjoyer :3

sharp furnace
halcyon beacon
#

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

burnt rover
#

you can assign the list comprehension to another variable and for loop over it again and print it however you want

sharp furnace
halcyon beacon
burnt rover
burnt rover
halcyon beacon
burnt rover
halcyon beacon
sharp furnace
burnt rover
#

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))
halcyon beacon
halcyon beacon
burnt rover
#

!e

fruits = ["Apple", "Banana", "Orange"]
formatted = ", ".join(fruits)
print(formatted)
last sandBOT
sharp furnace
burnt rover
halcyon beacon
#

Ok, ok

#

Interesting methods of doing this

halcyon beacon
#

!e

fruits = ["Apple", "Banana", "Orange"]
print(", ".join(fruits))
last sandBOT
halcyon beacon
#

OOHH IT WORKS

burnt rover
#

Indeed

#

I just put the extra variable to make it easier to read, you can still print it directly if you wish to

halcyon beacon
#

Then I chan change the separator to any str?

#

!e

fruits = ["Apple", "Banana", "Orange"]
formatted = "and ".join(fruits)
print(formatted)
burnt rover
#

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

halcyon beacon
burnt rover
halcyon beacon
#

!e

fruits = ["Apple", "Banana", "Orange"]
formatted = " and ".join(fruits)
print(formatted)
last sandBOT
halcyon beacon
#

Niceeee

burnt rover
#

!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=}")
last sandBOT
burnt rover
#

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?

halcyon beacon
#

That's an incredibly cool explanation. Ty.

burnt rover
#

No problemo

halcyon beacon
#

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

burnt rover
#

Alright, I'll still be on for while

halcyon beacon
amber torrent
last sandBOT
burnt rover
halcyon beacon
halcyon beacon
burnt rover
#

!e

player_data = {
    "name": "Saber",
    "coins": 900,
    "high_score": 10
}

print(player_data["name"])
print(player_data["coins"])
print(player_data["high_score"])
last sandBOT
burnt rover
#

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)
last sandBOT
burnt rover
#

Also the keys need to be of immutable data types only, such as integers, floats, strings, bools, tuples and such

amber torrent
#

frozenset is also fine to use and comes in handy sometimes

last sandBOT
#
Python help channel closed for inactivity

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.