Python_08_ 튜플(tuple)과 리스트(list) 공통점과 차이점

hyeong taek jo·2023년 9월 11일

Python

목록 보기
8/53

📌 공통점

  • 길이를 갖는다
  • 언패킹이 가능하다
  • index, count함수를 사용할 수 있다.

📌 차이점

  • 선언방식이 다르다

    a = [1,2,3]
    b= (1,2,3)

  • 리스트는 가변이지만 튜플은 불변이다.

  • 리스트는 append와 insert 같은 함수를 사용할 수 있지만 튜플은 안된다.

📌 특이점

  • 튜플(tuple)은 정의할때 괄호 붙이지 않아도 된다
  • 즉, 기본값이 튜플이다.
  • ex : colors = "red", "green", "blue", "yellow", "orange"

📌 리스트 예시

#    0,1,2
L = [1,2,3]
print(type(L))
print("len(L)->" , len(L))

print("L[1]=> ",L[1])
print("L[-1]=> ",L[-1]) #맨뒤
print("L[1:3]--> ", L[1:3]) # 1,2까지

print("L + L ==> ", L + L)
print("L * 3 ==> ", L * 3)

#   0 1 2       3
kk=[1,2,3,['a','b','c']]
print("kk=> ",kk)
print("kk[-1][1]==>",kk[-1][1])

<class 'list'>
len(L)-> 3
L[1]=> 2
L[-1]=> 3
L[1:3]--> [2, 3]
L + L ==> [1, 2, 3, 1, 2, 3]
L * 3 ==> [1, 2, 3, 1, 2, 3, 1, 2, 3]
kk=> [1, 2, 3, ['a', 'b', 'c']]
kk[-1][1]==> b


📌 튜플 예시

# Tuple은 List의 Read Only
# range : List나 Tuple를 사용, 저장하지 않더라도 특정범위의
#          숫자 시퀀스 생성
# range(start,stop,step)

L = range(10)   # 0 ~ 9

print(L)
print("L[::2]==>",L[::2]) # 처음부터 끝까지 2칸씩 뛰고
A = L[::2]
for aa in A:
    print('A-->',aa)

#tuple
t = (1,2,3)
print("len(t)--> ",len(t))
print("t[0]-->",t[0])
print(t[-1])
print(" t[0:2]-->", t[0:2])
print("t[::2]-> ",t[::2])

print("t + t + t ==> " , t + t + t)
print(t * 3)
print("L-->",L)

# Tuple==> 오류발생
# t[1] = 7
print("t[1]-->", t[1])

print(3 in t)

# tuple은 정의할때 괄호 붙이지 않아도 됨
colors = "red", "green", "blue", "yellow", "orange"
print('colors-->', colors)
print('colors len-->', len(colors))

# unpacking
a,b,c,d,e = colors  #팩킹되어 있는걸 불리되어 각각에 넣어주는것
print('a->',a)
print('c->',c)

the_last = colors[-1]
print('the_last=> ', the_last)

the_last = the_last.capitalize()    #첫문자 대문자
print('the_last capitalize-->', the_last)
profile
마포구 주민

0개의 댓글