본문 바로가기

python3/자료구조 & 알고리즘

파이썬 자료구조 : 모두를 위한 프로그래밍 - 리스트

2. 리스트

 

- 리스트의 각 항목들은 []로 둘러싸인다.

 

- 리스트 내에는 int, float, string, list 가 원소로 들어갈 수 있다.

 

- 빈 리스트를 만들려면 a =[] 혹은 a = list()

 

- 리스트의 항목들에는 인덱스 개념 적용이 가능하다.

 

- 리스트는 mutable!! 

lotto = [2, 14, 26, 41, 63]
print(lotto)
# [2, 14, 26, 41, 63]이 출력됨
lotto[2] = 28
print(lotto)
# [2, 14, 28, 41, 63]이 출력됨

- len() 함수 적용 가능

 

- range()는 0부터 특정값 - 1까지의 숫자로 이뤄지는 리스트를 반환하는 함수

 

- + 를 활용하여 리스트를 더할 수 있다.

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
# [1, 2, 3, 4, 5, 6]로 출력됩니다.

- 문자열 처럼 인덱스를 이용해 슬라이싱도 가능하다.

t = [9, 41, 12, 3, 74, 15]
print(t[1:3])
print(t[:4])
print(t[3:])
print(t[:])

# [41, 12]
# [9, 41, 12, 3]
# [3, 74, 15]
# [9, 41, 12, 3, 74, 15] 로 출력됩니다.

- dir() 메소드는 특정 타입에서 사용할 수 있는 메소드의 목록을 리스트의 형태로 보여준다.

x = list()
print(dir(x))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
# '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
# '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__',
# '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
# '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
# '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend',
# 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

- append() : 원소 하나 추가

- sort() : 항목 정렬하기

- in을 활용하여 특정값이 항목에 있는 지 확인 가능

 

- split() 함수를 이용해서 문자열을 구분하여 리스트 형태로 저장하는 것이 가능하다.

words2 = 'first;second;third'
stuff2 = words2.split()
print(stuff2)
# ['first;second;third']
stuff2 = words2.split(';')
print(stuff2)
# ['first', 'second', 'third']