List - 리스트 자료형
조회수 33.4k 등록일 2016.07.08 22:17:16

리스트는 파이썬의 sequence 자료형 중 가장 많이 사용되는 대표적인 자료 구조다.  각각의 값들은 요소 또는 원소라 부르며 콤마(,)로 구분한다.

원소마다 index가  0부터 순차적으로 할당되며 index를 통해 원소에 접근할 수 있다. 리스트는 일반적으로 대괄호([ ])로 선언하며 list()로도 선언 할 수 있다.




다음은 다양하게 선언한 예제이다.

  1. list0 = []
  2. list1 = ['one', 'two', 3, 4, 5]
  3. list2 = [1, 2, 3, 4, 5]
  4. list3 = ['one', 'two', 'three', 'four', 'five']
  5. list4 = ['one', 'two', ['three', 'four']]
  6. list5 = list(range(100)) 
  7. print(type(list0)) #

리스트는 list0 처럼 원소가 없거나 list1처럼 문자열과 숫자를 원소로 가질 수 있으며, 리스트안에 리스트를 가질 수 있다. 즉 Java나 C언어의 배열은 동일한 타입의 자료형만 원소로 가질 수 있지만 list는 여러가지 타입의 자료형을 원소로 가질 수 있다. 그러므로 배열과 리스트는 엄밀히 따지면 다르다.




원소에 접근하려면 대괄호([])안에 index를 입력하면 된다. 또한 음수 index로의 접근이 가능하고 일정 범위만큼 잘라 출력 할 수 있다. 

이를 슬라이스(slice)라 한다.

  1. print("list1[0] : ", list1[0])  # list1[0] :  one
  2. print(list1[2])  # 3
  3. print(list1[1:5])  # ['two', 3, 4, 5]
  4. print(list1[-1]) # 5

새로운 변수에 기존 변수를 대입한 경우 두 변수는 리스트 하나에 사용된 메모리를 참조한다. 즉, 새로운 메모리로 리스트를 할당하는게 아는게 아닌 두개의 변수가 메모리 하나를 참조하는 것이다.

  1. list6 = list1
  2. print(hex(id(list1))) # 0x188e20c
  3. print(hex(id(list6))) # 0x188e20c


파이썬에선 리스트를 쉽게 생성하기 위해 list comprehension를 제공한다. 

가령, 0부터 9까지 제곱된 수의 리스트를 생성한다고 하였을 경우 다음과  같은 방법이 있다.

  1. square = []
  2. for x in range(10):
  3.     square.append(x**2)
  4.  
  5. print(square)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

list comprehension를 사용하면 간결하게 위와 동일한 리스트를 생성 할 수 있다.

  1. squares = [x**2 for x in range(10)]
  2. print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

처리속도에서도 차이가 발생했다. 

프로파일러로는 cProfile를 사용하였으며 0부터 9999999의 수를 가지는 리스트의 모든 원소들을 제곱하여 처리 속도를 비교하였다.

  1. def square(list):
  2.     ~~~~
  3.  
  4. list = list(range(10000000))
  5. square(list)
  1. return [* i for i in list]
1.049

  1. return [** 2 for i in list]
1.282

  1. return map(lambda i: i ** 2, list)
3.569

  1. ret = []
  2. for i in list:
  3.     ret.append(** 2)
  4. return ret
3.133


list comprehension로 리스트를 생성한 것이 append로 생성하는 것보다 처리 속도가 빠른걸 알 수 있다.. 

list comprehension에 대해 더  자세한 사항은 공식 문서를 참고하길 바란다.




내장함수

함수
설명
len()
    
    리스트의 원소 수를 반환한다.
   syntax
    len(list)
   example

list1, list2, list3 = [1, 2, 3, 4, 5], [1, 'two'], ['one', ['two', 3]]

print("list1 : ", len(list1))  # list1 : 5

print("list2 : ", len(list2))  # list2 : 2

print("list3 : ", len(list2))  # list3 : 2

max()

    리스트 원소 중 최대 값을 반환한다. python2,3 에서  max() 함수의 가장 큰 차이점은 python2에선 원소의 자료형이 달라도     사용 가능했지만 python3에서는 같은 자료형에 대해서만 사용 가능하고 자료형이 같지 않으면 typeError가 난다.
   syntax
    max(list)
   example

list1, list2 = [1, 2, 3, 4, 5], ['one', 'two', 'three']

print("list1 : ", max(list1))  # list1 : 5

print("list2 : ", max(list2))  # list2 : two 

min()

    리스트의 원소중 최소값을 반환한다. python2, 3 의 차이점은 max() 함수와 동일하다.
   syntax
    min(list)
   example

list1, list2 = [1, 2, 3, 4, 5], ['one', 'two', 'three']

print("list1 : ", min(list1))  # list1 : 1

print("list2 : ", min(list2))  # list2 : one

list()

    list()는 시퀀스 자료형을 인수로 받아 새로운 리스트로 변환하여 반환한다. list()는 튜플을 리스트로 변환하는데 사용된다.
   syntax
    list(aTuple)
   example

aTuple = ('one', 'two', 'three')

list1 = list(aTuple)

print("List1 : ", list1)  # List1 :  ['one', 'two', 'three']




내장 메소드

메소드
설명
append()

    전달한 객체가 리스트의 마지막 요소로 추가된다.
   syntax
    list.append(obj)
   example

list1 = ['one', 'two', 'three', 'four', 'five']

list1.append('six')

print("List1 : ", list1)  # List1 :  ['one', 'two', 'three'] 

count()

    전달한 객체의 원소의 수를 확인한다.
   syntax
    list.count(obj)
   example

list1 = ['one', 'two', 'three', 'four', 'five']

print("List1 : ", list1.count('one'))  # List1 :  1 

extend()

    리스트 객체를 전달하여 한번에 여러개의 원소를 추가한다.
   syntax
    list.extend(seq)
   example

list1 = ['one', 'two', 'three']

list2 = ['four', 'five'];

list1.extend(list2)

print("List1 : ", list1)  # List1 :  ['one', 'two', 'three', 'four', 'five'] 

index()

    원소의 위치를 확인한다. 기본적으로 가장 낮은 인덱스를 반환하며 두번째, 세번째 매개변수로 검색하는 범위를 지정 할 수       있다.
   syntax
    list.index(obj)
   example

list1 = ['one', 'two', 'three', 'two', 'one', 'two']

print("Index : ", list1.index('two'))  # Index : 1

print("Index : ", list1.index('two', 4, 6))  # Index : 5 

insert()

    지정한 인덱스에 원소를 추가한다. 지정한 인덱스가 리스트의 길이보다 큰 경우 마지막에 추가된다.
   syntax
    list.index(index, obj)
   example

list1 = ['one', 'two', 'three', 'two', 'one', 'two']

list1.insert(1, 'insert1')

list1.insert(100, 'insert2')

print("List : ", list1) 

# List :  ['one', 'insert1', 'two', 'three', 'two', 'one', 'two', 'insert2'] 

pop()

    지정한 인덱스의 원소가 반환되며 리스트에서 제거 된다. obj를 전달하지 않으면 기본적으로 마지막 원소를 반환하며, obj를     전달하면 지정한 인덱스의 원소가 제거 후 반환된다.
   syntax
    list.pop(obj=list[-1])
   example

list1 = ['one', 'two', 'three']

list1.pop(1)

print("List : ", list1) # List :  ['one', 'three'] 

remove()

    리스트의 원소를 제거 한다. pop()과의 차이점으로는 제거만 하고 해당 원소를 반환하지 않는다.
   syntax
    list.remove(obj)
   example

list1 = ['one', 'two', 'three']

list1.remove('one')

print("List : ", list1) # List :  ['two', 'three'] 

reverse()

    리스트의 원소를 반전시킨다.
   syntax
    list.reverse()
   example

list1 = ['one', 'two', 'three']

list1.reverse()

print("List : ", list1) # List :  ['two', 'three'] 

sort()

    리스트의 원소를 재정렬 시킨다. python3 에서는 max() 함수와 마찬가지로 같은 자료형에서만 사용 가능하다. python3에    서의 서로 다른 자료형에 대한 정렬은 sorted 함수를 이용한 방법이 있다.
   syntax
    list.sort([func])
   example 

list1 = ['one', 'two', 'three']

list1.sort()

print("List : ", list1) # List :  ['one', 'three', 'two']

list1.sort(reverse=True)

print("List : ", list1) # List :  ['two', 'three', 'one']