Skip to content

Python Random: 난수, 선택, 샘플 생성하기

Updated on

랜덤 데이터 생성은 프로그래밍의 기본입니다 -- 플레이리스트 셔플과 설문 응답자 샘플링부터 몬테카를로 시뮬레이션과 테스트 데이터셋 생성까지. 하지만 Python의 random 모듈에는 수십 개의 함수가 있어서 잘못된 함수를 사용하기 쉽습니다. 정수가 필요할 때 random.random()을 호출하거나, 여러 고유 항목이 필요할 때 choice()를 사용하거나, random이 암호학적으로 안전하지 않다는 것을 잊으면 미묘한 버그나 보안 취약점이 발생할 수 있습니다.

Python의 random 모듈은 의사 난수 생성을 위한 포괄적인 도구 키트를 제공합니다. 이 가이드에서는 각 함수를 언제 사용해야 하는지 보여주는 명확한 예제와 함께 자주 필요한 모든 함수를 다룹니다.

📚

랜덤 정수

randint(a, b)

a <= N <= b(양쪽 끝점 포함) 범위의 랜덤 정수 N을 반환합니다.

import random
 
# Random integer between 1 and 10 (inclusive)
print(random.randint(1, 10))  # e.g., 7
 
# Simulate a dice roll
dice = random.randint(1, 6)
print(f"You rolled a {dice}")
 
# Generate random ages for test data
ages = [random.randint(18, 65) for _ in range(5)]
print(ages)  # e.g., [34, 52, 21, 45, 28]

randrange(start, stop, step)

range()와 유사하지만 랜덤 요소를 반환합니다. stop 값은 제외됩니다.

import random
 
# Random even number between 0 and 100
print(random.randrange(0, 101, 2))  # e.g., 42
 
# Random number from 0 to 9
print(random.randrange(10))  # e.g., 7
 
# Random multiple of 5 from 0 to 100
print(random.randrange(0, 101, 5))  # e.g., 35

랜덤 부동소수점

random()

[0.0, 1.0) 범위의 랜덤 부동소수점을 반환합니다.

import random
 
print(random.random())  # e.g., 0.7234...
 
# Scale to any range: random float between 10 and 20
value = 10 + random.random() * 10
print(value)  # e.g., 15.23...

uniform(a, b)

a <= N <= b의 랜덤 부동소수점 N을 반환합니다.

import random
 
# Random temperature between 98.0 and 99.5
temp = random.uniform(98.0, 99.5)
print(f"Temperature: {temp:.1f}F")  # e.g., Temperature: 98.7F
 
# Random price between 9.99 and 29.99
price = round(random.uniform(9.99, 29.99), 2)
print(f"Price: ${price}")

gauss(mu, sigma) -- 정규 분포

import random
 
# Generate normally distributed values (mean=100, std=15)
iq_scores = [round(random.gauss(100, 15)) for _ in range(10)]
print(iq_scores)  # e.g., [112, 95, 103, 88, 107, ...]

랜덤 선택

choice(seq)

비어 있지 않은 시퀀스에서 랜덤으로 하나의 요소를 반환합니다.

import random
 
colors = ['red', 'blue', 'green', 'yellow', 'purple']
print(random.choice(colors))  # e.g., 'green'
 
# Random character from a string
print(random.choice('abcdefghij'))  # e.g., 'f'

choices(population, weights, k)

복원 추출(중복 가능)로 k개 요소의 리스트를 반환합니다. 가중치를 지원합니다.

import random
 
# Pick 5 random colors (duplicates allowed)
colors = ['red', 'blue', 'green']
print(random.choices(colors, k=5))  # e.g., ['blue', 'red', 'blue', 'green', 'red']
 
# Weighted selection (red is 5x more likely)
weighted = random.choices(
    ['red', 'blue', 'green'],
    weights=[5, 1, 1],
    k=10
)
print(weighted)  # Mostly 'red'

sample(population, k)

비복원 추출(중복 없음)로 k개의 고유 요소를 반환합니다.

import random
 
# Lottery numbers: 6 unique numbers from 1-49
lottery = random.sample(range(1, 50), 6)
print(sorted(lottery))  # e.g., [3, 12, 27, 33, 41, 48]
 
# Random survey sample
employees = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
survey_group = random.sample(employees, 3)
print(survey_group)  # e.g., ['Diana', 'Alice', 'Frank']

choice vs choices vs sample

함수복원반환값사용 사례
choice(seq)N/A (단일 항목)하나의 요소랜덤으로 하나 선택
choices(pop, k=n)복원 추출n개 요소의 리스트가중치 랜덤, 시뮬레이션
sample(pop, k=n)비복원 추출n개 고유 요소의 리스트추첨, 랜덤 부분집합

셔플

shuffle(seq)

리스트를 제자리에서 셔플합니다. None을 반환합니다.

import random
 
deck = list(range(1, 53))  # 52 cards
random.shuffle(deck)
print(deck[:5])  # e.g., [37, 12, 48, 3, 21]
 
# Deal 5 cards
hand = deck[:5]
remaining = deck[5:]

시드와 재현성

시드를 설정하면 랜덤 출력이 재현 가능해집니다 -- 테스트와 디버깅에 필수적입니다.

import random
 
random.seed(42)
print(random.randint(1, 100))  # Always 81
print(random.random())          # Always 0.0744...
 
# Reset seed for same sequence
random.seed(42)
print(random.randint(1, 100))  # 81 again
print(random.random())          # 0.0744... again

시드를 사용할 시기

시나리오시드?이유
단위 테스트재현 가능한 테스트 결과
디버깅정확한 버그 재현
시뮬레이션 (분석)재현 가능한 실험
게임 (게임플레이)아니오플레이어는 진정한 랜덤을 기대
보안/암호아니오 (secrets 사용)시드는 출력을 예측 가능하게 만듦

테스트 데이터 생성

import random
import string
 
def random_string(length=10):
    """Generate a random alphanumeric string."""
    chars = string.ascii_letters + string.digits
    return ''.join(random.choices(chars, k=length))
 
def random_email():
    """Generate a random email address."""
    name = random_string(8).lower()
    domains = ['gmail.com', 'yahoo.com', 'outlook.com']
    return f"{name}@{random.choice(domains)}"
 
def random_user():
    """Generate a random user record."""
    first_names = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']
    last_names = ['Smith', 'Jones', 'Brown', 'Wilson', 'Taylor']
    return {
        'name': f"{random.choice(first_names)} {random.choice(last_names)}",
        'email': random_email(),
        'age': random.randint(18, 65),
        'score': round(random.uniform(0, 100), 1),
    }
 
# Generate 5 test users
users = [random_user() for _ in range(5)]
for user in users:
    print(user)

Random과 데이터 과학

데이터 분석 워크플로우에서 random 모듈은 샘플링, 부트스트래핑, 합성 데이터셋 생성에 도움이 됩니다. pandas와 결합하면 테스트 DataFrame을 빠르게 생성할 수 있습니다:

import random
import pandas as pd
 
random.seed(42)
n = 1000
 
df = pd.DataFrame({
    'age': [random.randint(18, 80) for _ in range(n)],
    'income': [round(random.gauss(50000, 15000), 2) for _ in range(n)],
    'category': random.choices(['A', 'B', 'C'], weights=[5, 3, 2], k=n),
})
print(df.describe())

랜덤 데이터셋의 인터랙티브 탐색을 위해, PyGWalker (opens in a new tab)는 모든 pandas DataFrame을 Jupyter 내에서 Tableau 스타일의 시각화 UI로 변환합니다:

import pygwalker as pyg
walker = pyg.walk(df)

보안 경고: random vs secrets

random 모듈은 보안 목적에 적합하지 않습니다. 시드가 알려지면 출력은 결정적이고 예측 가능합니다. 비밀번호, 토큰, 암호 애플리케이션에는 secrets 모듈을 사용하세요:

import secrets
 
# Cryptographically secure random token
token = secrets.token_hex(16)
print(token)  # e.g., 'a3f2b8c9d1e4f5a6b7c8d9e0f1a2b3c4'
 
# Secure random integer
secure_int = secrets.randbelow(100)
 
# Secure random choice
secure_choice = secrets.choice(['option1', 'option2', 'option3'])
특성randomsecrets
알고리즘메르센 트위스터 (PRNG)OS 엔트로피 소스 (CSPRNG)
결정적예 (시드 사용 시)아니오
속도빠름느림
용도시뮬레이션, 게임, 테스트비밀번호, 토큰, 암호
재현 가능예 (seed() 사용 시)아니오

FAQ

Python에서 랜덤 정수를 생성하는 방법은?

random.randint(a, b)를 사용하여 a와 b 사이(양쪽 포함)의 랜덤 정수를 얻습니다. 예를 들어, random.randint(1, 10)은 1부터 10까지의 숫자를 반환합니다. 상한을 제외하는 범위에는 random.randrange(start, stop)를 사용합니다.

random.choice와 random.sample의 차이점은?

random.choice(seq)는 하나의 랜덤 요소를 반환합니다. random.sample(population, k)는 비복원으로 k개의 고유 요소를 반환합니다. 중복이 허용되는 여러 항목을 선택하려면 random.choices(population, k=n)를 사용합니다.

랜덤 결과를 재현 가능하게 만드는 방법은?

난수를 생성하기 전에 random.seed(value)를 호출합니다. 같은 시드를 사용하면 매번 같은 난수 시퀀스가 생성됩니다. 단위 테스트와 디버깅에 필수적입니다.

Python의 random 모듈은 안전한가요?

아니요. random 모듈은 결정적이고 예측 가능한 메르센 트위스터 알고리즘을 사용합니다. 비밀번호나 토큰 같은 보안에 민감한 애플리케이션에는 암호학적으로 안전한 난수 소스를 사용하는 secrets 모듈을 대신 사용하세요.

Python에서 리스트를 랜덤으로 셔플하는 방법은?

random.shuffle(my_list)를 사용하여 리스트를 제자리에서 셔플합니다. 원본 리스트가 수정되고 None을 반환합니다. 원본 리스트를 변경하지 않으려면 먼저 복사본을 만드세요: shuffled = my_list.copy(); random.shuffle(shuffled).

결론

Python의 random 모듈은 모든 일반적인 랜덤화 요구를 충족합니다: 정수에는 randint, 부동소수점에는 uniform, 시퀀스에서 선택에는 choice/choices/sample, 재정렬에는 shuffle, 재현성에는 seed. 핵심적인 구분을 기억하세요: choices는 중복을 허용하고(복원 추출), sample은 허용하지 않습니다(비복원 추출). 그리고 보안에는 절대 random을 사용하지 마세요 -- 대신 secrets를 사용하세요.

📚