• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Python help

JTsyo

Lifer
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.
 
You could always

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

That eats all errors. There's probably a better and faster way, though.
 
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)

 
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))

 
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.
 
Back
Top