newhaneul

[Advanced Python Programming] Lecture 2. Sequence Data Types 본문

4. University Study/Advanced Python Programming

[Advanced Python Programming] Lecture 2. Sequence Data Types

뉴하늘 2026. 4. 12. 19:49
728x90

포스팅은 인하대학교 허혜선 교수님의 [202601-EEC3408-001] 고급파이썬프로그래밍을 수강하고 공부한 내용을 정리하기 위한 포스팅입니다.

 

  • range와 문자열도 안에 저장된 요소를 변경할 수 없음.
r = range(0, 10, 2)
r[0] = 3

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[1], line 2
      1 r = range(0, 10, 2)
----> 2 r[0] = 3

TypeError: 'range' object does not support item assignment
hello = "Hello, world!"
hello[0] = 'A'

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 2
      1 hello = "Hello, world!"
----> 2 hello[0] = 'A'

TypeError: 'str' object does not support item assignment

 

  • list와 달리 tuple, range, 문자열은 요소를 삭제할 수 없음
a = (1, 2, 3)
del a[1]

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[3], line 2
      1 a = (1, 2, 3)
----> 2 del a[1]

TypeError: 'tuple' object doesn't support item deletion

 

  • slice는 새롭게 객체를 만들어내며, range, tuple, list 모두 사용 가능함
a = [0, 10]
a[1:1]

[]

a = [0, 10]
a[4:1]

[]

 

  • 지정된 범위만큼 tuple을 잘라서 새로운 tuple을 생성하기
b = (0, 10, 20, 30)
b[0:2]

(0, 10)

 

  • 슬라이스를 통해 할당할 요소 개수가 적으면 그만큼 리스트의 요소 개수도 줄어듦
a = [0, 10, 20, 30, 40, 50]
a[1:4] = 'A'
a

[0, 'A', 40, 50]

 

  • 할당할 요소 개수가 많으면 그만큼 리스트의 요소 개수도 늘어남
a = [0, 10, 20, 30, 40, 50]
a[1:2] = ['A', 'B', 'C', 'D', 'E']
a

[0, 'A', 'B', 'C', 'D', 'E', 20, 30, 40, 50]

 

  • 인덱스 증가폭을 지정했을 때는 슬라이스 범위의 요소 개수와 할당할 요소 개수가 정확히 일치해야 함
a = [0, 10, 20, 30, 40, 50]
a[1::2] = ['A', 'B']
a

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[19], line 2
      1 a = [0, 10, 20, 30, 40, 50]
----> 2 a[1::2] = ['A', 'B']
      3 a

ValueError: attempt to assign sequence of size 2 to extended slice of size 3

 

  • tuple, range, 문자열은 슬라이스 범위를 지정하더라도 요소를 할당할 수 없음
a = (0, 10, 20, 30, 40, 50)
a[1:4] = ['A', 'B']
a

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[20], line 2
      1 a = (0, 10, 20, 30, 40, 50)
----> 2 a[1:4] = ['A', 'B']
      3 a

TypeError: 'tuple' object does not support item assignment
728x90