0
import random

a = [1, 2, 5, 3, 4, 5]
b = ["cat", "dog", "horse", "snake", "elephant", "goat"]

Hello! I am fairly new to programming. I'm sure it's not a difficult task, but I just can't find the solution.

I need a function in python to store a single random element from list "b" as a new list, but the elements that share the same index with elements from list "a" that are 5 must not be included in the random selection. So in my example, "horse" and "goat" must not be included in the random selection.

2

1 Answer 1

1

You can use a list comprehension and random.choice:

import random

a = [1, 2, 5, 3, 4, 5]
b = ["cat", "dog", "horse", "snake", "elephant", "goat"]
c = [random.choice([e for i,e in zip(a,b) if i != 5])]

Example output: ['dog']

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.