본문 바로가기
Python

[Python] Data type (2)

1. 리스트 자료형 List data type


1) 리스트란? What is a list?

  • 개별 변수는 정수면 정수, 실수면 실수 식으로 하나의 값만 저장하는 데 비해 리스트는 여러 개의 값을 순서가 있는 모음으로 저장
    Individual variables store only one value, such as an integer for an integer and float for float, Lists save multiple values as ordered vowels
  • 대괄호[] 안에 요소를 콤마,로 구분 Separate the elements in brackets [] with commas
리스트명 = [요소1, 요소2, 요소3, ...]
  • 리스트에 소속되는 각각의 값을 요소(element) 라고 함 Each value in the list is called an element
  • 리스트 안에는 어떠한 자료형도 포함시킬 수 있음 You can include any data type in the list
  • 비어 있는 리스트도 생성할 수 있음 You can also create empty lists

# 리스트 안에는 어떠한 자료형도 포함시킬 수 있음

You can include any data type in the list

a = [1, 2, 3]
b = ['AIFFEL', '화이팅']
c = [1, 2, 'AIFFEL', '화이팅']
d = [1, 2, ['AIFFEL', '화이팅']]

 

# 비어 있는 리스트로 생성할 수 있음

You can also create empty lists

e = []
e

 

# list() 함수를 사용해서 빈 리스트를 만들 수 있음

You can use the list() function to create an empty list

f = list()
f

 

 

2) 리스트의 인덱싱 & 슬라이싱 Indexing & Slicing of Lists

  • 문자열 때의 인덱싱 & 슬라이싱이 리스트에서도 가능 Indexing & slicing in strings is also possible in the list
  • 문자열 인덱싱 & 슬라이싱과 동일한 방법으로 다룰 수 있음Can be handled in the same way as string indexing & slicing
  • 리스트 안에 element인 리스트도 인덱싱할 수 있음 You can also index the list that is an element in the list

 

# 문자열과 동일하게 인덱싱

Indexing the same as the string

a = [1, 2, 3, 4, 5]
a[4]
>>>5

 

#음수일 경우

If it's negative number

a = [1, 2, 3, 4, 5]
a[-1]
>>>5

 

# 리스트 안에 element인 리스트도 인덱싱할 수 있음

You can index the list that is an element in the list

a = [1, 2, ['줴이든', '화이팅'], 3, 4]
a[2]
>>>['줴이든', '화이팅']

 

# '줴이든'만 인덱싱 할 수 있음 (리스트에서 한 번더 따로 인덱싱)

Only '줴이든' can be indexed (indexed separately once more from the list)

a[2][1]

 

3) 리스트 연산하기 List operation

리스트 연산은 문자열 연산의 의미와 동일 List operations are the same as string operations

  • 리스트 사이의 더하기(+) 연산자는 리스트를 합침 The plus (+) operator between lists combines the lists
  • 리스트 사이의 곱셈(*) 연산자는 리스트를 반복 Multiple (*) operators between lists repeat the list
  • 리스트 요소의 개수 len() 함수를 이용해서 구할 수 있음 The number of list elements can be obtained using the len() function

 

# 리스트 사이의 더하기(+) 연산자는 리스트를 합침

The plus (+) operator between lists combines the lists

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list1 + list2
>>>[1, 2, 3, 'a', 'b', 'c']

 

# 리스트 사이의 곱셈(*) 연산자는 리스트를 반복

Multiple (*) operators between lists repeat the list

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list2 * 2
>>>['a', 'b', 'c', 'a', 'b', 'c']

 

# 리스트 요소의 개수는 len() 함수를 이용해서 구할 수 있음

The number of list elements can be obtained using the len() function

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
len(list2 * 2)
>>>6

 

 

4) 리스트의 수정 & 삭제 Modifying and deleting lists

 

리스트의 요소는 수정(교체)할 수 있음 Elements in the list can be modified (replaced)

  • 리스트[인덱스] = 새 요소 List[index] = New Elements

 

예약어 del 을 이용해서 리스트 요소를 삭제할 수 있음 You can delete list elements using the reservation word del

  • del 객체 del object

예약어란? What is reserved word?

  • 특정 기능을 수행하도록 미리 예약되어 있는 단어 Words pre-scheduled to perform specific functions
  • 함수와 다르다 be different from a function
  • 추후에 다시 다룰 예정 Will be dealt with again later
 

 

# 리스트의 요소는 수정(교체)할 수 있음
Elements in the list can be modified (replaced)

a = ['a', 'b', 7, 'd']
a[2] = 'c'
a
>>>['a', 'b', 'c', 'd']

 

# 예약어 del 을 이용해서 리스트 요소를 삭제할 수 있음

You can delete list elements using the reservation word del

a = ['a', 'b', 7, 'd']
del a[2]
a
>>>['a', 'b', 'd']
 
 

2. 리스트 관련 함수들 Functions related to the list


함수 사용 예시 Example of using a function

  • 리스트명.함수() List name.Function ()

 

1) 추가 (append(x))

- 리스트 맨 마지막에 x를 추가하는 함수

Functions that add x at the end of the list

a = [1, 3, 5]
a.append(7)
a
>>>[1, 3, 5, 7]

 

# 요소는 모든 자료형이 가능

Elements can be any type of data

a = [1, 3, 5]
a.append([2, 4, 6, 8, 10])
a
>>>[1, 3, 5, 7, [2, 4, 6, 8, 10]]

 

# 다만 여러 요소를 넣으면 에러가 뜸

# However, errors occur when multiple elements are inserted

a = [1, 3, 5]
a.append(9, 11)
a
>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_13/1245024677.py in <module>
      2 # [window] : 
      3 
----> 4 a.append(9, 11)
      5 a

TypeError: list.append() takes exactly one argument (2 given)

 

 

2) 정렬(sort())

# sort 함수는 괄호 안에 아무것도 넣지 않음

sort function puts nothing in parentheses

a = [5, 2, 3, 4, 1]
a.sort()
a
>>>[1, 2, 3, 4, 5]

 

 

3) 뒤집기(reverse())

# reverse 함수는 괄호 안에 아무것도 넣지 않음

Reverse function puts nothing in parentheses

a = ['h', 'e', 'l', 'l', 'o']
a.reverse()
>>>['o', 'l', 'l', 'e', 'h']

 

 

4) 위치 반환(index(x))

# index(x) 함수는 리스트에 x가 있으면 x의 위치 값을 돌려줌

The index(x) function returns the location value of x if there is x in the list

a = ['h', 'e', 'l', 'l', 'o']
a.index('e')
>>>1

 

# 중복인 요소가 있을 때 확인해보기 (중복인 경우, 가장 앞 자리의 요소의 위치만 나타냄)

Check when duplicate elements are present (if duplicate, only indicates the position of the element in the front row)

a = ['h', 'e', 'l', 'l', 'o']
a.index('l')
>>>2

 

 

# 없는 요소를 x에 있을 때 확인

Check when an element that is not present is in x

a = ['h', 'e', 'l', 'l', 'o']
# a.index('b')
>>>
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_13/28368362.py in <module>
      3 
      4 a = ['h', 'e', 'l', 'l', 'o']
----> 5 a.index('b')

ValueError: 'b' is not in list

 

 

5) 요소 삽입(insert(a, b))

# insert(a, b)는 a번째 위치에 b 요소를 삽입

Insert(a, b) inserts the b element into the a-th position

a = [1, 3, 5, 7, 9]
a.insert(5, 11)
a
>>>[1, 3, 5, 7, 9, 11]

 

6) 요소 제거(remove(x))

# remove(x)는 요소 x를 삭제

remove(x) deletes element x

a = ['e', 'x', 't', 'e', 'n', 'd']
a.remove('x')
a
>>>['e', 't', 'e', 'n', 'd']

 

# 중복인 요소가 있을 때 확인

Check when duplicate elements exist

a = ['e', 'x', 't', 'e', 'n', 'd']
a.remove('e')
a
>>>['x', 't', 'e', 'n', 'd']

pop() returns the last element of the list and deletes it

a = [1, 2, 3]
a.pop()
>>>3

a
>>> [1, 2]

 

8) 특정 개수 세기(count(x))

# count(x)는 리스트 안에 요소 x가 몇 개 있는지 개수를 세고 그 개수를 반환

count(x) counts how many elements x are in the list and returns the number of elements

a = ['h', 'e', 'l', 'l', 'o']
a.count('l')
>>>2

 

9) 리스트 확장(extend(x))

# extend(x)에서 리스트 x를 기존 리스트에 연결

Connect list x to existing list in extension(x)


# x는 리스트만 올 수 있음

x can only come to the list type

a = [1, 2, 3]
a.extend([4, 5, 6])
a
>>>[1, 2, 3, 4, 5, 6]

 

# a.extend(b) 는 a += b 와 동일

a.extend(b) is equal to a + = b

a = [1, 2, 3]
b = [4, 5, 6]
a += b
a
>>>[1, 2, 3, 4, 5, 6]

 

 

3.튜플 자료형 Tuple data type


1) 튜플이란? What is a Tuple?

  • 여러 개의 값의 모음이라는 점에서 리스트와 비슷하지만 수정할 수 없다 는 점에서 다름.
    Similar to the list in that it is a collection of multiple values, but different in that it cannot be modified.
  • 소괄호() 안에 요소를 콤마,로 구분. 튜플명 = (요소1, 요소2, 요소3, ...)
    Separate elements in brackets () with commas. Tuple name = (element 1, element 2, element 3, ...)
  • 소괄호()를 생략해도 무방. 튜플명 = 요소1, 요소2, 요소3, ...
    It's okay to omit the brackets (). Tuple name = Element 1, Element 2, Element 3, ...
  • 튜플에 소속되는 각각의 값 또한 요소(element) 라고 함
    Each value belonging to a tuple is also called an element
  • 튜플 안에는 어떠한 자료형도 포함시킬 수 있음
    Any data type can be included in the tuple
  • 비어 있는 튜플도 생성
    Create empty tuples

 

2) 튜플에서 가능한 것과 불가능한 것 What's possible and what's impossible in Tuple

 

2.1) 가능한 것 what's possible

  • 튜플 요소를 인덱싱 & 슬라이싱할 수 있음 Allows indexing & slicing of tuple elements
  • + 연산자로 튜플을 연결할 수 있음 ( +) Operators can connect tuples
  • * 연산자로 튜플을 반복할 수 있음 ( *) Operators can repeat tuples

 

# 튜플 요소를 인덱싱 & 슬라이싱할 수 있음

Allows indexing & slicing of tuple elements

tu1 = 1, 2, 3, 4, 5
tu1[0]
>>>1
tu1 = 1, 2, 3, 4, 5
tu1[:3]
>>>(1,2,3)

 

# + 연산자로 튜플을 연결할 수 있음

(+) Operators can connect tuples

tu1 = 1, 2, 3, 4, 5
tu2 = 6, 7, 8, 9
tu1 + tu2
>>>(1, 2, 3, 4, 5, 6, 7, 8, 9)

 

# * 연산자로 튜플을 반복할 수 있음

(*) Operators can repeat tuples

tu1 = 1, 2, 3, 4, 5
tu1 * 2
>>>(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

 

 

2.2) 불가능한 것 What's impossible

  • 튜플 요소를 변경하거나 삭제하는 것은 불가능 It is impossible to change or delete tuple elements

 

# 튜플 요소는 변경이 불가능

Tuple elements cannot be changed

tu1 = (2, 4, 6)
tu1[0] = 1
>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_13/2906908922.py in <module>
      3 
      4 tu1 = (2, 4, 6)
----> 5 tu1[0] = 1

TypeError: 'tuple' object does not support item assignment

 

# 튜플 요소는 삭제가 불가능

Tuple elements cannot be deleted

tu1 = (2, 4, 6)
del tu1[0]
>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_13/889789391.py in <module>
      3 
      4 tu1 = (2, 4, 6)
----> 5 del tu1[0]

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

3) 튜플을 사용하는 이유 Why use a tuple

  • 튜플의 내부 구조가 단순한 만큼 더 적은 메모리를 사용하고 읽는 속도도 빠름
    As simple as the tuple's internal structure is, it uses less memory and reads faster
  • 편집할 수 없기 때문에 안정적
    Stable because it can't be edited

'Python' 카테고리의 다른 글

[Python] Loop  (0) 2023.10.04
[Python] Conditional statement  (1) 2023.10.03
[Python] Data type (3)  (0) 2023.09.28
[Python] Data type (1)  (0) 2023.09.22
[Python] Basics and Terms  (0) 2023.09.21