str = "Hello"
lst = list(str)
print(lst) # ['H', 'e', 'l', 'l', 'o']
tpl = (10, 20, 30)
lst = list(tpl)
print(lst) #[10, 20, 30]
<<값 추가>>
tpl = (10, 20, 30)
lst = list(tpl) ❓튜플 -> 리스트
lst.append(40) ❓리스트 값추가
tpl = tuple(lst) ❓리스트 -> 튜플
print(tpl) ❓최종 튜플 출력 # (10, 20, 30, 40)
키값만 반환)d = {'one':1, 'two':2, 'three':3}
lst = list(d)
print(lst) # ['one', 'two', 'three']
s = {1, 2, 3}
lst = list(s)
print(lst) # [1, 2, 3]
↪️(참조값 (주소) 복사 vs 객체값 (데이터 자체) 복사)
[Ex1]shallow copy, [Ex2]deep copy
* 얕은 복사(shallow copy)
: 변수가 가지고 있는 참조값 복사 -> 동일한 메모리 주소 참조
⤿ (*참조값: 메모리 내 List 객체의 주소값)
(=)A = [1, 2, 3, 4, 5]
B = A ❓변수A '참조값'복사 -> B
print(B) #[1, 2, 3, 4, 5]
>B[1] = 100 ❓같은 참조값 = 하나의 리스트 변수를 가리킨다
print(A) #[1, 100, 3, 4, 5] ❓원본list 영향(O)
print(B) #[1, 100, 3, 4, 5]
[ : ]<<이중 리스트>> -얕은 복사
A = [[1,2], [3,4]]
B = A[:]
print(A) #[[1,2], [3,4]]
print(B) #[[1,2], [3,4]]
>B[0][0] = '변경'
print(A) #[['변경', 2], [3, 4]] ❓원본list 영향(O)
print(B) #[['변경', 2], [3, 4]]
copy() 메서드를 이용한 얕은 복사<<이중 리스트>>
A = [1, 2, 3, [4, 5]]
B = A.copy()
print(A) #[1, 2, 3, [4, 5]]
print(B) #[1, 2, 3, [4, 5]]
>B[3][0] = 99
print(A) #[1, 2, 3, [99, 5]] ❓원본list 영향(O)
print(B) #[1, 2, 3, [99, 5]]
[ : ]<<단일 리스트>>
original = [1, 2, 3, 4, 5]
copied = original[:] ❓'처음~끝' 복사
print(original) #[1, 2, 3, 4, 5]
print(copied) #[1, 2, 3, 4, 5]
copied[0] = 10
print(copied) #[10, 2, 3, 4, 5]
print(original) #[1, 2, 3, 4, 5] ❓원본list 영향(X)
copy() 메서드를 이용한 깊은 복사<<단일 리스트>>
original = [1, 2, 3, 4, 5]
copied = original.copy()
print(original) #[1, 2, 3, 4, 5]
print(copied) #[1, 2, 3, 4, 5]
copied[0] = 10
print(copied) #[10, 2, 3, 4, 5]
print(original) #[1, 2, 3, 4, 5] ❓원본list 영향(X)
copy 모듈의 deepcopy() 함수 이중리스트의 내부 리스트까지 모두 복사 ↪️ so. 원본리스트와 독립적 복사본 생성import copy ⚡
A = [[1, 2, 3], [4, 5, 6]]
B = copy.deepcopy(A) ⚡
print(A) #[[1, 2, 3], [4, 5, 6]]
print(B) #[[1, 2, 3], [4, 5, 6]]
>B[0][0] = 100
print(A) #[[1, 2, 3], [4, 5, 6]]
print(B) #[[100, 2, 3], [4, 5, 6]] ❓복사본B만 변경
append() : 리스트 끝에 요소 추가fruits = [ 'apple', 'banana', 'cherry' ]
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
insert(index, value) : 지정 index 위치에 value 삽입fruits.insert(1, 'grape')
print(fruits) # ['apple', 'grape', 'banana', 'cherry', 'orange']
remove(value) : 첫번째로 일치 항목 제거A = ['apple', 'banana', 'cherry', 'banana', 'banana', 'grape']
A.remove('banana')
print(A) #['apple', 'cherry', 'banana', 'banana', 'grape']
pop() : 마지막 항목 제거/반환B = A.pop()
print(A) # ['apple', 'cherry', 'banana', 'banana']
print(B) # grape
pop(index) : 해당 index 항목을 제거/반환B = A.pop(1)
print(A) #['apple', 'banana', 'banana']
print(B) #cherry
del 키워드를 이용한 해당 index 항목 제거fruits = ['apple', 'banana', 'cherry', 'banana', 'banana', 'grape']
del fruits[1]
print(fruits) #['apple', 'cherry', 'banana', 'banana', 'grape']
슬라이싱[:]을 이용한 특정 범위 항목 제거fruits = ['apple', 'banana', 'cherry', 'banana', 'banana', 'grape']
fruits[1:3] = [] #1번 ~ 3번 인덱스 전까지 제거
print(fruits) #['apple', 'banana', 'banana', 'grape']
del 키워드 ➕ 슬라이싱[:] 이용한 특정 범위 항목 제거A = ['apple', 'banana', 'cherry', 'banana', 'banana', 'grape']
del A[1:3]
print(A) #['apple', 'banana', 'banana', 'grape']
💬 Python(1) 확인
in 연산자존재하는지 확인fruits = ['apple', 'banana', 'cherry']
⤺❓ banana가 fruits 리스트에 포함되어 있는지 확인
if 'banana' in fruits:
print('바나나가 있습니다.')
else:
print('바나나가 없습니다.')
not in 연산자존재하지 않는지 확인if 'orange' not in fruits:
print('오렌지가 없습니다.')
else:
print('오렌지가 있습니다.')

count(value) : 포함된 요소(value) 개수 반환fruits = ['apple', 'banana', 'cherry', 'bnana', 'orange', 'banana' ]
banana_count = fruits.count('banana')
print(banana_count) # 3
sort() : 리스트의 요소 - 정렬fruits = ['apple', 'banana', 'cherry', 'bnana', 'orange', 'banana' ]
fruits.sort()
print(fruits) # ['apple', 'banana', 'banana', 'bnana', 'cherry', 'orange']
reverse() : 리스트의 요소 - 역순 뒤집기fruits = ['apple', 'banana', 'cherry', 'bnana', 'orange', 'banana' ]
fruits.reverse() # fruits[::-1]과 동일
print(fruits) #['banana', 'orange', 'bnana', 'cherry', 'banana', 'apple']
clear() : 모든 요소 제거 fruits = ['apple', 'banana', 'cherry', 'bnana', 'orange', 'banana' ]
fruits.clear()
print(fruits) # []
age = input('나이를 입력하세요: ')
if int(age) < 19:
print('애들은 가라')
a = 1234 * 4
b = 13456 / 2
if a > b:
print('a')
else:
print('b') ❓if, a > b = 'a' /if X, 'b'
distance = int(input("상대방과의 거리를 입력 하세요>>>"))
if distance >= 200:
print("Q")
elif distance >=100:
print("w")
else:
print("e") ❓거리 200 이상 : Q/거리 100 이상 : W/그 외 : E
<<계절을 입력하면 영어로 번역되는 프로그램>>
print('계절 : 봄, 여름, 가을, 겨울')
seasonStr = input('계절 입력 : ')
if seasonStr == '봄' :
print('{} : {}'.format('봄', 'Spring'))
elif seasonStr == '여름' :
print('{} : {}'.format('여름', 'Summer'))
elif seasonStr == '가을' :
print('{} : {}'.format('가을', 'Fall'))
elif seasonStr == '여름' :
print('{} : {}'.format('겨울', 'Winter'))
else:
print('검색할 수 없습니다.')
: 조건문 안에 또 다른 조건문이 들어있는 형태
중첩 조건문
<<Ex.01>> 출퇴근 시 이용하는 교통수단에 따라 세금을 감면해주는 정책을 세우려고 한다.
다음 내용에 맞게 프로그램 만들기
<다음>
1) 출퇴근 대상자인가?
2) 출퇴근 대상자가 아니면 세금 변동 없음
3) 출퇴근 대상자이면
⤷ 도보, 자전거 : 세금 5% 감면
버스, 지하철 : 세금 3% 감면
자가용 : 추가 세금 1% 부과
: 조건에 따라 값을 간결하게 반환하는 방식으로, if-else 조건식을 한 줄로 표현 ▶️ 문법 : "if 조건식 else"
age = 20
status = "성인" if age >= 18 else "미성년자"
⤷ ❓조건에 따라 변수 status에 "성인" 또는 "미성년자" 값을 할당
print(status) #성인
💬 Python(1, 1-1) 확인
: list, tuple, string, set, dict 등에서 특정 값 존재 여부 확인 연산자
<<at.리스트>>
fruits = [ 'apple', 'banana', 'cherry' ]
if 'apple' in fruits:
print('apple이 포함되어 있습니다.')
if 'grape' not in fruits:
print('grape이 포함되어 있지 않습니다.')
<<at.문자열>>
message = 'Hello, world!'
print("Hello" in message) # True
print("hello" in message) # False <= 대소문자 구분
<<at.튜플>>
members = ('James', 'Robert', 'Lisa', 'Mary')
print('Lisa' in members) # True
print('Lisa' not in members) # False
<<at.딕션너리 ▶️ 키 포함 여부>>
person = {"name": "John", "age": 36, "country": "Norway"}
print("name" in person) # True
print("John" in person) # False
print("gender" in person) # False ❓key 기준으로 검색
: 시퀀스(list,tuple,str 등)의 각 요소를 변수에 순회하며, 반복해서 실행할 코드 블럭 실행
✔️고정 범위 내에서 반복
for 변수 in 시퀀스:<<list 순회>>
A = ['apple', 'banana', 'cherry']
for B in A: ❓in 시퀀스(A)에서 for반복-변수(B)에 객체 값 하나씩 할당
print(B) #apple ❓반복 실행할 코드
#banana
#cherry
print(A) #['apple', 'banana', 'cherry'] ❓요소3개-> print()함수 3번 반복
#['apple', 'banana', 'cherry']
#['apple', 'banana', 'cherry']
<<str. 순회>
word = "hello"
for char in word:
print(char) # h ❓"hello" 각 문자 순회
# e
# l
# l
# o
<<rage() 함수를 이용한 순회>>
#range(n) : 0부터 n-1까지의 숫자 생성
#range(n, m) : n부터 m-1까지의 숫자 생성
#range(n, m, s) : n부터 m-1까지의 숫자 생성 + s만큼 증가
>for i in range(5):
print(i) # 0
# 1
# 2
# 3
# 4
>for i in range(0,5,2):
print(i) # 0
# 2
# 4
⭐실습⭐ 구구단 2단부터 9단까지 출력 코드 작성.
: 조건이 참(True)인 동안 코드 블록 지속 반복
✔️반복 횟수 명확X, 조건에 따라 반복 지속
while 조건식:
반복할 코드
변화식
<<count가 5보다 작은 동안 count를 출력하고 1씩 증가시키는 코드>>
count = 0
while count < 5:
print(count)
count += 1 #0부터 4까지 출력
<<숫자 1 ~ 100 출력 코드>>
num = 1
while num <= 100:
print(num)
num = num + 1 #1부터 100까지 출력

: 반복문 내부에 또다른 반복문 사용하는 구조
<<구구단 2~9단>>
dan = 2
while dan < 10: ⚡
num = 1
while num < 10: ⚡
print(f'{dan} * {num} = {dan * num}')
num += 1
print()
dan += 1
<<모양 만들기>>
print("=========================")
for i in range(1,10,1): ⚡
for j in range(1,i,1): ⚡
print("*", end= '')
print( "\n")