0

I have a List in python. I want to add a new item to this list. But I want to shuffle (insert to a random place in list with saving the order of other elements ) it to The list exactly. I want Something like this:

A = [2,4,3,6,7,3,3,4,6]
B = 5
shuffle(A,B)

How can I do this?

Karim Pazoki
  • 951
  • 1
  • 13
  • 34
  • It's really not clear what you want this shuffle function to do. It sounds like you want to use the `insert` list method? – Andrew Dec 06 '18 at 09:34
  • What would be the expected result of "shuffling it to the list exactly"? – Bernhard Dec 06 '18 at 09:35
  • Possible duplicate of [Shuffling a list of objects](https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects) – Mr Singh Dec 06 '18 at 09:40

2 Answers2

3

You can just add new element to list and shuffle list

A = [2,4,3,6,7,3,3,4,6]
B = 5
A.append(B)
shuffle(A)

or... if you want to insert B to random position:

from random import randint

A.insert(randint(0, len(A)), B)
Andersson
  • 51,635
  • 17
  • 77
  • 129
1

You can use random to shuffle a list:

import random

A = [2,4,3,6,7,3,3,4,6]
B = 5

A.append(B)  # adds B to A
random.shuffle(A)  # shuffle the list
print(A)

returns:

[4, 3, 4, 6, 7, 3, 6, 5, 3, 2]
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47