지난번 포스팅에서는 파이썬의 자료형 중에서 리스트(Python List)의 생성 및 기본 사용법에 대해서 알아보았습니다.  


이번 포스팅에서는 이어서 파이썬 리스트의 내장 함수와 메소드(Python List built-in functions and methods)에 대해서 소개하겠습니다. 


리스트 자료형이 다른 유형의 자료를 한번에 다룰 수 있기 때문에 리스트를 잘 사용하면 코드를 한결 깔끔하게 짤 수 있습니다.  그리고 리스트 내의 요소(element)를 갱신할 수 있기 때문에 데이터 분석할 때 리스트가 애용된다고도 했는데요, 이번 포스팅에서 소개하는 리스트 내장 함수(list built-in functions)와 다양한 기능을 제공하는 메소드(list methods)도 리스트 자료형이 자주 사용되고 또 중요한 자료형인 이유 중의 하나입니다. 






1. 파이썬 리스트 내장 함수 (Python List built-in functions)


 1-1. len(list) : 리스트의 전체 길이


for loop 문에서 자주 사용하곤 합니다. 



# (1-1) len(list) : Gives the total length of the list

>>> list1 = [1, 2, 3]

>>> list2 = ['a', 'b', 'c', 'd']

>>> len(list1)

3

>>> len(list2)

4

 




  1-2. max(list) : 리스트 안에 있는 요소 중에서 최대값 반환 (문자인 경우 알파벳 순서 기준)



# (1-2) max(list) : Returns item from the list with max value

>>> list1 = [1, 2, 3]

>>> max(list1)

3

>>> 

>>> list2 = ['a', 'b', 'c', 'd']

>>> max(list2)

'd'

 




  1-3. min(list) : 리스트 안에 있는 요소 중에서 최소값 반환 (문자인 경우 알파벳 순서 기준)



# (1-3) min(list) : Returns item from the list with min value

>>> list1 = [1, 2, 3]

>>> min(list1)

1

>>> 

>>> list2 = ['a', 'b', 'c', 'd']

>>> min(list2)

'a'

 




  1-4. list(seq) : 튜플을 리스트 자료형으로 변환



# (1-4) list(seq) : Converts a tuple into list

>>> tup = ('aaa', 'bbb', 'ccc') # tuple

>>> tup

('aaa', 'bbb', 'ccc')

>>> 

>>> list_tup = list(tup) # converting a tuple into list

>>> list_tup

['aaa', 'bbb', 'ccc']

>>> type(list_tup)

<class 'list'>

 




 1-5. cmp(list1, list2) : 리스크 안의 요소 비교하여 불리언값 반환 (단, Python 3.x 버전에서는 삭제됨)



Python 2.x 버전에서는 두 개의 리스트 원소를 비교해서 불리언값을 반환하는 cmp(list1, list2) 라는 내장 함수가 있었습니다만, Python 3.x 버전에서는 삭제되었습니다.  이전 cmp(list1, list2) 내장 함수의 기능은 아래의 '==' 연산자를 사용하면 Python 3.x 버전에서 동일한 결과를 얻을 수 있습니다. 



# cmp() has been removed in py3.x.

>>> list1 = [1, 2, 3]

>>> list2 = ['a', 'b', 'c', 'd']

>>> list3 = [1, 2, 3]

>>> 

>>> list1 == list2

False

>>> list1 == list3 

True

 






2. 파이썬 리스트 메소드 (Python List methods)


  2-1. list.append(obj) : 기존 리스트에 1개의 요소를 이어 붙이기



# (2-1) list.append(obj) : Appends object obj to list

>>> list1 = [1, 2, 'a', 'b']

>>> list1.append('c') # append an element

>>> list1

[1, 2, 'a', 'b', 'c']

 



append() 메소드를 사용할 때는 괄호 안에 추가하려는 요소를 1개만 써야 하며, 2개 이상 쓰면 TypeError 가 발생합니다. 



>>> list1.append('c', 'd') # TypeError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

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

 




  2-2. list.extend(seq) : 기존 리스트에 다른 리스트를 이어 붙이기



# (2-2) list.extend(seq) : Appends the contents of seq to list

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

>>> list3 = [3, 3, 4, 'd', 'd']

>>> 

>>> list3.extend(list2)

>>> list3

[3, 3, 4, 'd', 'd', 1, 2, 'a', 'b', 'c']

 




  2-3. list.count(obj) : 리스트 안에 obj 가 몇 개 들어있는지 세어서 개수를 반환



# (2-3) list.count(obj) : Returns count of how many times obj occurs in list

>>> list3 = [3, 3, 4, 'd', 'd', 'd', 'e']

>>> list3.count(3)

2

>>> list3.count('d')

3

 




  2-4. list.index(obj) : 리스트에서 obj 요소 값이 있는 가장 작은 index 값 반환



# (2-4) list.index(obj) : Returns the lowest index in list that obj appears

>>> list4 = [1, 2, 'a', 'b', 'c', 'a']

>>> 

>>> list4.index('a')    

2

>>> list4.index('c')   

4

 



만약 리스트 안에 없는 값을 obj 에 넣어서 list.index(obj) 를 실행하면 ValueError 가 발생합니다. 



# ValueError: 'ggg' is not in list

>>> list4.index('ggg') # ValueError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: 'ggg' is not in list

 




 2-5. list.insert(index, obj) : 기존 리스트의 index 위치에 obj 값을 삽입



# (2-5) list.insert(index, obj) : Inserts obj into list at offset index

>>> list5 = [1, 2, 'a', 'b', 'c']

>>> list5

[1, 2, 'a', 'b', 'c']

>>> 

>>> list5.insert(3, 'kkkk')

>>> list5

[1, 2, 'a', 'kkkk', 'b', 'c']

 




  2-6. list.pop(obj=list[-1]) : 기존 리스트에서 마지막 요소를 제거하고, 제거된 마지막 요소를 반환



# (2-6) list.pop(obj=list[-1]) : Removes and returns last object or obj from the list

>>> list6 = [1, 2, 'a', 'b', 'c']

>>> list6.pop() # removes the last element

'c'

>>> list6

[1, 2, 'a', 'b']

 



pop() 의 괄호 안에 정수(integer)를 넣어주면, 기존 리스트에서 해당 정수 위치의 index 값을 제거하고, 제거된 index 위치 요소의 값을 반환합니다. 



>>> list6 = [1, 2, 'a', 'b', 'c']

>>> list6.pop(2) # removes the element of the index

'a'

>>> list6

[1, 2, 'b', 'c']

 




 2-7. list.remove(obj) : 기존 리스트에서 remove(obj) 메소드 안의 obj 객체를 제거



# (2-7) list.remove(obj) : Removes the given object from the list

>>> list7 = [1, 2, 'a', 'b', 'c']

>>> list7.remove(1)

>>> list7

[2, 'a', 'b', 'c']

>>> 

>>> list7.remove('a')

>>> list7

[2, 'b', 'c']




remove() 메소드는 괄호 안에 단 1개의 argument 만을 사용하며, 2개 이상을 넣으면 TypeError 가 발생합니다. 



# TypeError: remove() takes exactly one argument

>>> list7 = [1, 2, 'a', 'b', 'c']

>>> list7.remove(1, 'a') # TypeError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: remove() takes exactly one argument (2 given)

 




 2-8. list.reverse() : 리스트의 객체를 리스트 안에서 순서를 반대로 뒤집기



# (2-8) list.reverse() : Reverses objects of list in place

>>> list8 = [1, 2, 'a', 'b', 'c']

>>> list8.reverse()

>>> 

>>> list8

['c', 'b', 'a', 2, 1]

 




  2-9. list.sort() : 리스트의 객체를 리스트 안에서 순서대로 정렬하기 (디폴트 오름차순)


sort() 메소드의 디폴트오름차순(ascending) 입니다. 



>>> list9 = [3, 1, 9, 4, 2, 8]

>>> list9.sort() # ascending order, default setting

>>> list9

[1, 2, 3, 4, 8, 9]

 



내림차순(descending)으로 정렬하고 싶다면 list.sort(reverse=True) 처럼 옵션을 설정해주면 됩니다. 



>>> list9 = [3, 1, 9, 4, 2, 8]

>>> list9.sort(reverse=True) # descending order

>>> list9

[9, 8, 4, 3, 2, 1]

 



문자는 알파벳 순서로 정렬합니다. 


# sorting character by alphabetical order

>>> list9_2 = ['c', 'a', 'b']

>>> list9_2.sort()

>>> list9_2

['a', 'b', 'c']

 



숫자와 문자가 섞여있는 리스트에 sort() 메소드를 적용하면 TypeError 가 발생합니다. 


# TypeError when applying sort() method for list with number and character

>>> list9_3 = [3, 1, 9, 'c', 'a', 'b']

>>> list9_3.sort()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: '<' not supported between instances of 'str' and 'int'

 



많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. ^^


다음번 포스팅에서는 파이썬 자료형 중에서 튜플(Tuple)의 기본 사용법에 대해서 알아보겠습니다. 





728x90
반응형
Posted by Rfriend
,