본문 바로가기
Python

[Python] list (sequence type) : summary

by ds31x 2023. 7. 12.

list (Sequence Type) : Summary

listordered mutable collection으로, collection을 위한 python data type들 중 가장 많이 사용된다.

C에서의 array와 같이 가장 기본적인 collection임.
단, heterogeneous item을 가질 수 있으며,
여러 methods를 가지는 객체라는 점이 array와 다름.

 

Python에서 대표적인 sequence type인 것은 다음 세가지임.

  • list : mutable sequence
  • tuple : immutable sequence
  • string : immutable text sequence

sequence type은
indexing이 element의 위치(순서)에 의해 이루어지기 때문에
순서(order)가 매우 중요함.

 

listtuple은 매우 유사해서 tuple을 immutable list라고 부르기도 함.

  • list는 square bracket []를 이용.
  • tuple은 parentheses ()를 이용.

개별 item 접근 및 갱신

a = [0,1,2,3,4]
print(a[1])  # 1
print(a[-1]) # 4
  • zero-based indexing (or numbering)임.
  • square bracket을 통한 indexing.
  • negative index를 이용하여 뒤에서부터 접근이 가능함. [-1]은 맨 마지막 요소를 가르킴.
a = [0,1,2,3,4]
a[-2] = 100 # replace the next-to-last element
print(a) # [0,1,2,100,4]

slicing

list의 특정 부분을 한번에 지정하여 값을 얻어냄.

x = [-1,0,1,2,3,4,5,6,7,8,9]

first_three  = x[:3]  # [-1, 1, 2]
three_to_end = x[3:]  # [3, 4, ..., 9]
one_to_four  = x[1:5] # [1, 2, 3, 4]
last_three   = x[-3:] # [7, 8, 9]

without_first_and_last = x[1:-1] # [1, 2, ..., 8]
copy_of_x = x[:]  # [-1, 1, 2, ..., 9]

print(f'{first_three=}')
print(f'{three_to_end=}')
print(f'{one_to_four=}')
print(f'{last_three=}')
print(f'{without_first_and_last=}')
print(f'{copy_of_x=}')
  • colon 앞이 start index 이고 뒤는 end_index +1 이 주어짐.
  • slicing으로 얻어진 list는 새로운 id를 갖는 list이지만, item들은 같은 원본의 object들을 가르키고 있음.
    • slicing 이후 특정 idx의 item에 assignment를 할 경우,
    • 원본이 바뀌는 것이 아닌 해당 item이 새로운 object를 참조하게 된다.
    • 주의할 건, NumPy등에서는 실제로 array기반으로 동작하여 slicing은 단순히 viewer에 불과하기 때문에 이 경우 원본도 변경된다.

결과는 다음과 같음.

first_three=[-1, 0, 1]
three_to_end=[2, 3, 4, 5, 6, 7, 8, 9]
one_to_four=[0, 1, 2, 3]
last_three=[7, 8, 9]
without_first_and_last=[0, 1, 2, 3, 4, 5, 6, 7, 8]
copy_of_x=[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

list에서 slicing은 새로운 객체를 생성함.

slicing으로 얻은 b에서 item할당은 원본에 영향을 주지 않음. b는 새로운 id의 list임.


in membership operation

sequence type에서는 in 연산의 효율이 좋지 못함

  • 처음부터 끝까지 다 확인을 해야하기 때문에 권장되지 않음.
  • set 의 사용을 추천.

 

또한 string의 경우와 달리 list에서는 single item 단위로만 in 연산이 동작한다. 다음의 예를 참고하라.

l = [ 1, 2, 3, 4, 5, 6]

if 1 in l:
  print('True')
else:
  print('False')

if [2,3,4] in l:
  print('True')
else:
  print('False')

 

결과는 다음과 같음.

True
False

 

참고로 string의 경우 다음과 같음.

s = "abcedfg"
sub_s = "ce"

print(f'{(sub_s in s)=}') # (sub_s in s)=True

정렬

a = [ 3, 5, 1, 4, 2 ]
c = sorted(a) # a는 그대로임. 정렬된 새로운 list object가 생성되어 반환됨.
a.sort()      # a가 정렬되어 update됨.
print(c)
print(a)
print(a is c) # a와 c가 같은 object인가 (id가 같은지)
print(a == c) # a와 c의 값이 같은지 체크.
  • a.sort() 메소드를 호출시 반환값이 None임. 반환값으로 a를 받지 않도록 주의할 것.
  • sort() 메소드는 자신이 호출된 object를 갱신하므로 immutable인 tuple에서는 제공되지 않음.
  • 역순으로 정렬을 원한다면 a.sort(reverse = True)를 이용한다.
  • 기본적으로 오름차순, 알파벳순임.

결과는 다음과 같음.

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
False
True

 


tuple을 item으로 가지는 list의 정렬에서는
key 파라메터에 function 객체를 지정하여

item 의 여러 요소 중에서 무엇으로 정렬할지를 정할 수 있음.

a = [(1,'a'), (0,'b'), (2,'c')]

a.sort(key = lambda x: x[0]) # item인 tuple의 첫번째 요소를 기준으로 정렬.
print(a) # [(0, 'b'), (1, 'a'), (2, 'c')]
a.sort(key = lambda x: x[1]) #item인 tuple의 첫번째 요소를 기준으로 정렬.
print(a) # [(1, 'a'), (0, 'b'), (2, 'c')]
  • 위의 예에서는 lambda function을 사용했으나, def를 통한 function을 지정해도 된다.

관련 ipynb.

https://gist.github.com/dsaint31x/6794486c7fca7ab0632098c1989d0af8

 

py_list_summary.ipynb

py_list_summary.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com


같이 읽어보면 좋은 자료들

2024.04.15 - [분류 전체보기] - [Python] collections.abc

 

[Python] collections.abc

2023.10.06 - [Pages] - [Python] Collections collections.abc 와 Python의 DataStructure. Python의 Data structure는 실제적으로 collections.abc 라는 abstract base class (abc) mechanism를 통한 hierarchy로 구성된다. 일반적으로 list, tuple

ds31x.tistory.com

2024.03.15 - [Python] - [DL] Tensor 간의 변환: NumPy, PyTorch, TensorFlow

 

[DL] Tensor 간의 변환: NumPy, PyTorch, TensorFlow

pytorch와 numpy의 경우, 텐서를 추상화하고 있는 tensor와 ndarray 를 제공하며, 이 둘은 zero-copy interoperability를 가진다고 말할 수 있을 정도로 상호호환이 가능하다. TensorFlow도 numpy와 상당히 연관되어

ds31x.tistory.com

 

반응형