Search

Python List, Tuple Basic

카테고리
Programming
태그
Python
게시일
2023/09/07
수정일
2024/02/24 09:40
시리즈
python_syntax
1 more property

리스트(List)

기본적으로 제공하는 시퀀스 자료구조입니다. C 혹은 Java에서 사용하는 배열(Array)와 유사하고, Stack, Queue, Deque를 구현할 때 자주 사용됩니다. List는 다음과 같은 특징을 같습니다.
List는 여러 Element로 구성돼 있음
문자열처럼 element들에 순서가 있으며 이를 index라고 표현함

Examples

리스트를 표현하는 방법은 ‘[]’ 대활호를 이용하여 데이터를 감싸는 형태입니다. 감싸진 데이터들을 요소(element)라고 하며 다음과 같이 선언할 수 있습니다.
대괄호 [, ]로 element를 둘러 표현함
element들의 순서가 있음
element들의 생성, 삭제, 수정이 가능함
_string = "ThisStringIsLikeList" 의 경우 indexing을 통해 순서에 맞는 문자로 접근(조회)할 수 있지만, 생성, 삭제, 수정이 불가능하기 때문에 list라고 표현하기 어렵습니다.
# init list >>> a = [] >>> a = list() # String # _string = "ThisStringIsLikeList" <-- can indexing but not list >>> _string = ['T', 'h', 'i', 's', 'S', 't', 'r', 'i', 'n', 'g', 'I', 's', 'L', 'i', 'k', 'e', 'L', 'i', 's', 't'] # Integers in list >>> _integers = [1,2,3,4,5,6,7,8,9,0] # Any value in List >>> _anything = [1,2,"a", "b", [1,2,3], ['something', 'anything']]
Python
복사

indexing

list에서 기본적으로 index를 이용하여 조회, 수정, 삭제, 생성이 가능합니다.
# List indexing >>> _integers = [1,2,3,4,5,[6,7,8,9,0]] >>> _integers [1,2,3,4,5,[6,7,8,9,0]] # select element >>> _integers[0] 1 >>> _integers[5][1] 7 # edit element >>> _integers[0] = 11 >>> _integers [11,2,3,4,5,[6,7,8,9,0]] # delete element >>> del _integers[0] >>> _integers [2,3,4,5,[6,7,8,9,0]] # add element >>> _integers.append(10) >>> _integers [2,3,4,5,[6,7,8,9,0],10] >>> _integers.insert(0,999) # insert(index, value) >>> _integers [999,2,3,4,5,[6,7,8,9,0],10] >>> _integers.insert(123456789, 55) # if index is out of range, append value. [999,2,3,4,5,[6,7,8,9,0],10,55]
Python
복사
문자열에서는 기본적으로 indexing을 통한 값 조회는 가능하나, list에서 제공하는 생성, 삭제, 수정이 불가능합니다. 이를 위해서는 ‘str’을 ‘list’로 변환하여 컨트롤하는 방법이 있습니다.
# String indexing >>> _string = "ThisStringIsLikeList" >>> _string ThisStringIsLikeList >>> _string[0] T >>> _string[0] = "A" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment # String to list >>> _string = list("ThisStringIsLikeList") >>> _string ['T', 'h', 'i', 's', 'S', 't', 'r', 'i', 'n', 'g', 'I', 's', 'L', 'i', 'k', 'e', 'L', 'i', 's', 't'] >>> _string[0] = "A" >>> _string ['A', 'h', 'i', 's', 'S', 't', 'r', 'i', 'n', 'g', 'I', 's', 'L', 'i', 'k', 'e', 'L', 'i', 's', 't']
Python
복사

Slicing

list slicing은 ‘나누기’라는 의미로써, 변수 뒤에 [start:end:step]을 붙여 문자를 나눌 수 있습니다.
start : 시작 index
end : 끝 index ( 해당 인덱스까지는 포함하지 않고 slicing 됨)
step : index간 step으로 간격을 의미함
>>> _string = "ThisStringIsLikeList" >>> _string[3:] 'sStringIsLikeList' >>> _string[:3] 'Thi' >>> _string[0:10:2] 'TiSrn' >>> _string[:10:2] 'TiSrn'
Python
복사

Calculation

list형태의 값들 끼리 element의 값을 서로 연산하여 표현이 가능합니다.
# Add >>> A = [1,2,3] >>> B = [4,5,6] >>> A + B [1,2,3,4,5,6] # Multiple >>> A * 3 [1,2,3,1,2,3,1,2,3] # TypeError >>> A + "hello_world" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python
복사

Etc.

list에서는 기본적으로 제공되는 편리하고 다양한 기능이 있습니다. 정렬(sort), 역순(reverse), 검색(index), 삭제(remove), 추출(pop), 카운팅(count), 덧셈(extend) 등이 있습니다.
>>> A = [2,5,7,1,2,3,5,8,7,8,9] >>> A.sort() >>> A [1, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9] >>> A.reverse() >>> A [9, 8, 8, 7, 7, 5, 5, 3, 2, 2, 1] >>> A.index(2) # Find where is value `2`, return first index number. 8 >>> A.remove(2) # like del A[A.index(2)] >>> A [9, 8, 8, 7, 7, 5, 5, 3, 2, 1] >>> A.pop() # Pop last value 1 >>> A.pop(0) # Pop value in index `9` 9 >>> A [8, 8, 7, 7, 5, 5, 3, 2] >>> A.count(7) 2 >>> A.extend([1,2]) >>> A [8, 8, 7, 7, 5, 5, 3, 2, 1, 2]
Python
복사

튜플(Tuple)

Tuple은 element들을 소괄호 (, )로 감싸 표현하며, List와 비슷한 역할을 하지만 조금은 다른 특성을 가지고 있습니다. Tuple에서는 List처럼 element들의 순서가 있지만 변경이 불가능합니다.
소괄호 (, )로 element를 둘러 표현함
단, 소괄호로 표현하지 않아도 Tuple을 선언할 수 있음
element들의 순서가 있음
element들의 생성, 삭제, 수정이 불가능함

Examples

>>> _tuple1 = (1,2,"a","b") >>> _tuple2 = 1,2,"a","b" >>> _tuple1 (1, 2, 'a', 'b') >>> _tuple2 (1, 2, 'a', 'b')
Python
복사

Indexing

Tuple은 기본적으로 Indexing을 이용하여 조회가 가능합니다.
>>> _tuple1 = (1,2,"a","b") # Indexing >>> _tuple1[0] 1 >>> _tuple1.index("a") 2
Python
복사

Slicing

Tuple도 List와 동일하기 slicing을 지원합니다.
>>> _tuple1 = (1,2,"a","b") >>> _tuple1[1:2] (2,)
Python
복사

Etc

기본적인 Indexing은 가능하나 Tuple 형태로는 수정, 삭제, 생성이 불가능합니다. 단, 새로운 튜플을 뒤로 이어붙이는 기능은 제공합니다. 기본적으로 Tuple 끼리의 덧셈, 곱셈 연산은 제공하며, 기본 덧셈 연산에 대한 내용은 다음과 같습니다.
>>> _tuple1 = (1,2,"a","b") >>> _tuple2 = 3,4,"c","d" # Add tuples >>> _tuple1 + _tuple2 (1, 2, 'a', 'b', 3, 4, 'c', 'd') >>> _tuple1 += _tuple2 >>> _tuple1 (1, 2, 'a', 'b', 3, 4, 'c', 'd') >>> _tuple1 + ("f") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate tuple (not "str") to tuple >>> _tuple1 + ("f",) (1, 2, 'a', 'b', 3, 4, 'c', 'd', 'f') >>> _tuple1 + "f", Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate tuple (not "str") to tuple # Multiple tuples >>> (1,2,3,"a","B") * 3 (1, 2, 3, 'a', 'B', 1, 2, 3, 'a', 'B', 1, 2, 3, 'a', 'B')
Python
복사

How to edit tuple?

Tuple은 type 형태가 튜플일 경우에는 리스트와 같은 indexing을 통한 수정, 삭제, 생성이 불가능합니다. 따라서 이와 같은 기능이 필요할 경우 tuple의 형태를 list로 치환 후 적절한 수정 작업을 진행할 수 있습니다.
>>> _tuple1 = (1,2,"a","b") >>> _listed_tuple1 = list(_tuple1) >>> _listed_tuple1.insert(2, "insert!!") >>> _tuple1 = tuple(_listed_tuple1) >>> _tuple1 (1, 2, 'insert!!', 'a', 'b')
Python
복사