alexa
Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

If element is in list, return another unique element in python ?

If element is in list, return another unique element in python ?

In your inner loop, you can consider using the following try statement (to replace the if x in subs):

 from random import randrange
try:
     idx = subs.index(x)
     while True:
          a = randrange(0, len(subs))
          if a != idx:
               break
     print(subs[a])
except ValueError:
     pass 

The try suite tries to find the index in subs with corresponding element equal to the word x.

  • In the event that x is not found, a ValueError is raised and we quietly ignore it.
  • In the event that x is found, idx is assigned the corresponding index. Then, we assign a random integer in [0, len(subs) - 1] (i.e. the set of valid indices for subs) to a until a is not equal to idx. Once a is not equal to idx, we break out of the loop and print subs[a].

Drawing inspiration from @Mad Physicist, it would be better if the try suite were replaced with

 a = randrange(0, len(subs) - 1)
a += a >= subs.index(x) 

which assigns a to a random integer in [0, len(subs) - 1) and then increments a by 1 if a >= idx is true; otherwise (i.e. if a < idx is true), a is unchanged. If this change is made, the try statement becomes

 try:
     a = randrange(0, len(subs) - 1)
     a += a >= subs.index(x)
     print(subs[a])
except ValueError:
     pass 

A slight optimization would be to simply catch all exceptions with except: (replacing except ValueError:). See, for example, this answer. The gist of it is that if an except clause has an expression (here, ValueError), it needs to be evaluated and tested against the raised exception from the try suite. An expression-less except clause (as in except:) does not have to do this additional step. I would not recommend making catching all exceptions a habit, however -- it is context-specific.

Example Session

Suppose that

 words = ["green", "eggs", "and", "ham", "hewwo", "woahwa"]
bigLsts = [['herro', 'hewwo', 'holas'], ['woah', 'woahwa', 'whatda']] 

A session might yield output

 herro
whatda

60 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online