LavaTime
LavaTime

Reputation: 75

Is there a way to shuffle a list in python?

I'm trying to make a simple encryptions using a random abc to convert it But i'm having a problem with the Random library.

  1. Tried using some other answers that people asked on this issue on StackOverflow and none worked...
  2. Tried updating pip and tried updating random (which you cannot apparently use pip because the Random library pre-downloaded with python) tried the problematic code in python Shell and still the same problem...
import random
def random(st = 'i love cats')
    abc = 'abcdefghijklmnopqrstuvwxyz'
    randomabc = abc
    random.shuffle(randomabc)
    print(randomabc)

the expected output is a random order of the ABC the actual output is an error (the code stops before the print because of the error)

Upvotes: 0

Views: 225

Answers (3)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You cannot shuffle a string, it is an immutable object which cannot be changed once it is assigned. Instead you need to convert it to a list (A mutable object), shuffle the list via random.shuffle which shuffles the list in-place, and then convert the list back to the string.

import random

abc = 'abcdefghijklmnopqrstuvwxyz'

#Convert string to list
li = list(abc)

#Shuffle the list inplace
random.shuffle(li)

#Convert list to string
print(''.join(li))

The output will be

dpfozwhyxalebnqrmstcjvuigk
qgjefyrahobpnxtzmsdkwivlcu
nchkriewsuxdzyjfgvpblomtqa
.....

In addition to it, another alternative (a one-liner) is to use random.sample to pick len(abc) unique samples, and join all of them in a string (Thanks @JonClements) but it's more suited for a one off reshuffle

print(''.join(random.sample(abc, len(abc))))

Upvotes: 1

ruohola
ruohola

Reputation: 24038

Since abc is a string, which are immutable (you cannot change it in-place) you cannot do it like that.

Instead you have to:

  1. split the string into a list of characters.

  2. shuffle that list

  3. join the character list back into a string

import random

abc = 'abcdefghijklmnopqrstuvwxyz'
ls = list(abc)
random.shuffle(ls)
abc = ''.join(ls)

print(abc)

Example output:

erbkvownuhcmfljtgqpyiazdxs

Also: Never name your functions or .py files with names clashing with the standard library. In this case your function is the same name as the random module, and that is a huge problem.

Upvotes: 2

Olvin Roght
Olvin Roght

Reputation: 7812

As I mentioned in comments, you should give your functions names different from python keywords, imported modules, class names, etc. Try to rename your method form random to random_alphabet.

import random

def random_alphabet(st = 'i love cats'):
    pass

Upvotes: 1

Related Questions