파이썬 - 변수 선언, 복사

ahncheer·2025년 1월 31일

python

목록 보기
6/25

0. 자료형 간단 복습

print("type(1) : ", type(1))
print("type('abc') : ", type('abc'))
print("type([1, 2, 3]) : ", type([1, 2, 3]))
print("type((1, 2, )) : ", type((1, 2, )))
print("type({1: 'a'}) : ", type({1: 'a'}))
print("type(set('hello')) : ", type(set('hello')))
print("type(bool('')) : ", type(bool('')))

1. 변수 만들기

변수 이름 = 변수에 저장할 값

2. 변수 여러개 한번에 선언

# 2-1. 튜플 사용
x1, x2 = ('apple', 'banana')
print('x1 : ', x1, ', x2 : ', x2) 

# 2-1-1. 튜플 > 괄호생략
(x3, x4) = 'apple', 'banana'
print('x3 : ', x3, ', x4 : ', x4) 

# 2-2. 리스트 사용
[x5, x6] = ['happy', 'life']
print('x5 : ', x5, ', x6 : ', x6) 

# 2-3. = 기호 사용
x7 = x8 = 'python'
print('x7 : ', x7, ', x8 : ', x8) 

3. 변수 복사하기 (같은 주소 공유)

a = [1, 2, 3]
b = a
print('b :', b)
print('a is b : ', a is b)
print('id(a) : ', id(a), ', id(b) : ', id(b))
print('---')

4. 변수 복사하기 (값만 복사. 주소 다름)

# 4-1. 리스트 한정 사용가능. [:] 사용
c = [4, 5, 6]
d = c[:] 
print('c is d : ', c is d)
print('id(c) : ', id(c), ', id(d) : ', id(d))
print('---')

# 4-2. copy 모듈 사용 (튜플 사용 불가)
from copy import copy
e = set('hello')
f = e.copy() # copy(e)로도 사용가능
print('e is f : ', e is f)
print('id(e) : ', id(e), ', id(f) : ', id(f))

5. 간단하게 값 두개 바꾸기

y1 = 'yellow'
y2 = 'black'
y1, y2 = y2, y1
print('y1 : ', y1, ', y2 : ', y2)

참고 링크 : https://wikidocs.net/18

profile
개인 공부 기록용.

0개의 댓글