how do I delete values from a list taking user input ?
>>> animals = [a,c] = [1,2]
>>> print(a)
1
>>> print©
2
>>> print(animals)
[1, 2]
>>> pick = input("Enter a value to delete: ")
Enter a value to delete: a
>>> animals.remove(pick)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
Also:
fish = [a,b,c,d,e,f] = [1,2,3,4,5,6]
How can delete 2 values at a time from this list using random.sample(listname,2)
Thanks
Try this
animals = [a,c] = [1,2]
print(animals)
pick = input("Enter a value to delete: ")
if pick == 'a':
animals.remove(1)
elif pick == 'b':
animals.remove(2)
else:
print('Invalid input')
print(animals)
What is the reason writing this line:
>>> animals = [a,c] = [1,2]
What is wrong with simple way:
>>> lst = ['a', 'b', 'c']
>>> lst.remove('a')
>>> lst
['b', 'c']
@Evil_Patrick: Think what will happen if it's a huge list(s) or if the list(s) changes...
@metro17: this is wrong by design. user should not be concerned with internals (i.e. they are not expected to know anything about variable names)
if you look at
animals = [a,c] = [1,2]
-
a
and
c
are variable names.
You should use proper data structure like dict:
animals = {'rabbit':1, 'fox':2}
print(animals)
pick = input("Enter animal to delete: ")
del animals[pick]
print(animals)
Output:
{'rabbit': 1, 'fox': 2}
Enter animal to delete: fox
{'rabbit': 1}
Just iterating buran code for fun:
>>> s = {'rabbit', 'fox'}
>>> s.remove(input('Enter animal to delete: '))
Obviously code is dependant on user input correctness.
thanks Buran
import random
>>> Alldict = {'clubsacesmin':1,'clubsacesmax':11,'diamondsacesmin':1,'diamondsacesmax':11}
>>> n = 0
>>> while n < 2:
... pick = (random.choice(list(Alldict)))
... del Alldict(pick)
... print(Alldict)
...
File "<stdin>", line 3
SyntaxError: can't delete function call
I am unable to delete each randomly picket item ?
How can this be fixed
thanks
got it working.
import random
Alldict = {'clubsacesmin':1,'clubsacesmax':11,'diamondsacesmin':1,'diamondsacesmax':11}
n = 0
while n < 2:
pick = (random.choice(list(Alldict)))
del (Alldict[pick])
print(Alldict)
n = n + 1
import random
Alldict = {'clubsacesmin':1,'clubsacesmax':11,'diamondsacesmin':1,'diamondsacesmax':11}
Dealerdict = {}
Playerdict = {}
n = 0
while n < 2:
pick = (random.choice(list(Alldict)))
Dealerdict.update(pick.keys(),Dealerdict.update(pick.values())
del (Alldict[pick])
print(Alldict)
n = n + 1
How can add key value pair to the new dictionary here?
how can I randomly pick a key,value pair from a dictionary?
..and then assign it to a variable and use the variable to delete from the dictionary
..and use the key value pair captured in the variable to add to another dictionary
..and use the variable to print keys and values ?
a = (random.choice(list(Alldict)))
print(a)
The above statement gives me only the key but not the value?