DEV Community

Cover image for Embaralhando e Sorteando em Python
Daniel Nogueira
Daniel Nogueira

Posted on

10 1

Embaralhando e Sorteando em Python

Embaralhar pode ser uma função interessante em um programa, ainda mais se queremos garantir mais aleatoriedade em um conjunto de dados que serão escolhidos.

Importaremos a biblioteca random e criaremos uma lista de inteiros para ser usada em nosso exemplo.

import random
lista = [10,20,30,40,50]
Enter fullscreen mode Exit fullscreen mode

E por fim, para embaralhar a lista, usaremos a o método shuffle. Se exibirmos a lista, poderemos ver os elementos embaralhados.

random.shuffle(lista)
print(lista)
Enter fullscreen mode Exit fullscreen mode

Exemplo de resultado:

[50, 40, 20, 10, 30]
Enter fullscreen mode Exit fullscreen mode

E para fazer uma escolha aleatória, usamos o método choice.

x = random.choice(lista)
print(x)
Enter fullscreen mode Exit fullscreen mode

Exemplo de resultado:

30
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series