D
D
dontgiveafcuk2018-03-05 15:16:11
Python
dontgiveafcuk, 2018-03-05 15:16:11

How to shuffle indexes in a list at program start?

I have a list:
list = ['word1','word3','word4']
how to shuffle content ?
so that, for example, word4 becomes at index 0. And word 1 at index 3.
I need the indexes to constantly change places with each other when the program starts

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
koldop, 2018-03-05
@koldop

import random
lst = ['word1','word3','word4']
random.shuffle(lst)
print(lst) # ['word3', 'word4', 'word1']

And it's better not to use list as a variable name ;)

N
Nitrius, 2018-03-05
@Nitrus

import random
random.shuffle(array)

D
dvlprjv15, 2018-03-05
@dvlprjv15

The free online book "Invent your own computer games with Python" (Author: Al Sweigart) uses the following trick in chapter 8 :

import random    #это модуль генератора случайных чисел

# с помощью метода .split() создаете список (это чтобы не задалбываться с печатанием кавычек)

words = 'ant baboon badger bat bear beaver camel cat clam cobra'.split()

# записываете в переменную случайно выбранный индекс элемента списка words

wordIndex = random.randint(0, len(words) - 1)

# выводите на экран случайно выбранное слово из списка

print(words[wordIndex])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question