Python help

JTsyo

Lifer
Nov 18, 2007
12,068
1,159
126
So say I have a list L = [1,2,3,4] Now I pick a random number and delete it. L.remove(n) how would I check to be sure that n was in L? Is there a logic function I could use that would check the entire list?
Currently if n is not in L, then the program gives an error.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,835
4,815
75
You could always

try:
L.remove(n)
except:
err = 1

That eats all errors. There's probably a better and faster way, though.
 

tfinch2

Lifer
Feb 3, 2004
22,114
1
0
Why not get the length of the list and only generate a number within bounds?

import random

listLen = len(L)
L.remove(random.randint(0, listLen - 1)

 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,835
4,815
75
Originally posted by: tfinch2
Why not get the length of the list and only generate a number within bounds?
Remove looks for the value, not the index. But I see where you're going with this. dir(L) and L.pop.__doc__ told me the rest of what I needed to know. Try this:

import random

listLen = len(L)
L.pop(random.randint(0, listLen - 1))

 

JTsyo

Lifer
Nov 18, 2007
12,068
1,159
126
I used the L.count(n) and it worked with what I wanted. The really application isn't random numbers, just threw that in as an example.