Paste a randomly selected item from one list into another

I have two lists: list1=["a","b","c","d"]

and list2=["z","y","x","w"]

.

I would like to take a random element list1

and place it in list2[1]

.

I write list2.insert(1,random.sample(list1,1))

but I receive['z',['b'],'y','x','w']

How do I remove parentheses around 'b'

?

+3


source to share


3 answers


Use random.choice

, random.sample

for the pile elements:



list2.insert(1, random.choice(list1))

      

+9


source


>>> import random
>>> list1 = ["a", "b", "c", "d"]
>>> list2 = ["z", "y", "x", "w"]
>>> list2.insert(1, random.sample(list1, 1)[0])
>>> list2
['z', 'b', 'y', 'x', 'w']

      



Just changing your pattern, but indexing the 0th element to remove the curly braces.

+1


source


Here you go, assuming you want to remove it from list1:

list2.insert(1, list1.pop(random.randrange(len(list1)))

      

0


source







All Articles