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.

Mico
  • 33
  • 3
  • Welcome to Stack Overflow! Please take the [tour]. What have you already tried, and where are you stuck? There are at least three parts to this task: 1) compare `a` and `b` side-by-side, 2) filter `b`, 3) pick from the filtered items. Which do you need help with? If this is homework, please read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/4518341) For more tips, see [ask]. You can [edit] to add details. – wjandrea Nov 13 '21 at 21:59
  • Related: [filter a list based on values in another list](/q/63785948/4518341), [How can I randomly select an item from a list?](/q/306400/4518341) – wjandrea Nov 13 '21 at 22:04

1 Answers1

2

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']

mozway
  • 194,879
  • 13
  • 39
  • 75