Jump to content

(Python) why does this not work?

GreaseySleezy

<fruits = ["apple", "banana", "cherry"]
x, y, z = fruits

print(fruits - "apple")>

Link to comment
Share on other sites

Link to post
Share on other sites

You can't perform such math-like operation between a list and a regular string, what you want is to use the remove method from list

 

print(fruits.remove("apple"))

FX6300 @ 4.2GHz | Gigabyte GA-78LMT-USB3 R2 | Hyper 212x | 3x 8GB + 1x 4GB @ 1600MHz | Gigabyte 2060 Super | Corsair CX650M | LG 43UK6520PSA
ASUS X550LN | i5 4210u | 12GB
Lenovo N23 Yoga

Link to comment
Share on other sites

Link to post
Share on other sites

15 minutes ago, GreaseySleezy said:

<fruits = ["apple", "banana", "cherry"]
x, y, z = fruits

print(fruits - "apple")>

Just read the error message. TypeError: unsupported operand type(s) for -: 'list' and 'str'

Meaning: you can't subtract a string from a list.

 

But you can remove it if you want:

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits

print(fruits) #output is this: ["apple", "banana", "cherry"]
fruits.remove("apple")
print(fruits) #output is this:  ["banana", "cherry"]

 

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, igormp said:

print(fruits.remove("apple"))

This won't work. The remove function doesn't return any value. It will just print None.

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, shadow_ray said:

This won't work. The remove function doesn't return any value. It will just print None.

Oops, my bad, always forget which methods return a new item and which ones modify in place :old-tongue:

FX6300 @ 4.2GHz | Gigabyte GA-78LMT-USB3 R2 | Hyper 212x | 3x 8GB + 1x 4GB @ 1600MHz | Gigabyte 2060 Super | Corsair CX650M | LG 43UK6520PSA
ASUS X550LN | i5 4210u | 12GB
Lenovo N23 Yoga

Link to comment
Share on other sites

Link to post
Share on other sites

You can do that sort of behaviour with sets:

 

fruits = {"apple", "banana", "cherry"}
print(fruits - {"apple"})
# or to actually remove it.
fruits -= {"apple"}
print(fruits)

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×