하나의 변수에 새로운 값을 할당하게 되면 기존의 값은 사라지고 그 자리에 새로운 값이 대체된다.
즉, 하나의 변수에는 하나의 값만이 할당이 가능하다.
하지만, 하나의 변수에 여러 값을 넣는 것이 가능하도록 하는 것이 컬렉션이다.
문자열처럼, 리스트(list)는 값의 순서(sequence)이다.
문자열에서 값은 문자지만 리스트에서는 임의 자료형(type)도 될 수 있다. 리스트 값은 요소(elements)나 때때로 항목(items)으로 불린다. 리스트를 생성하는 방법은 여러 가지가 있다.
가장 간단한 방법은 대괄호[
]
로 요소를 감싼다.
리스트는 컬렉션의 한 종류이다.
1. 리스트의 각 항목들은 [ ]
로 둘러싼다.
2. 리스트 내의 항목들에 대한 구분은 ,
(콤마)로 구분한다.
friends = ['Joseph', 'Glenn', 'Sally']
carryon = ['socks', 'shirt', 'perfume']
3. 리스트 내에 또 다른 리스트를 내포할 수 있다.
colors = ['red', ['yellow','blue'], 'black']
4. 비어 있는 리스트를 만들 수 있다.
emptyList = []
5. 리스트의 항목들에 인덱스 값으로 접근할 수 있다.
colors = ['red', ['yellow','blue'], 'black']
print(colors[0]) # red 출력
6. 리스트의 항목들은 바뀔 수 있다.
lotto = [2, 14, 26, 41, 63]
print(lotto)
# [2, 14, 26, 41, 63]이 출력됨
lotto[2] = 28
print(lotto)
# [2, 14, 28, 41, 63]이 출력됨
friends = ['Joseph', ' Glenn', 'Sally']
print(len(friends))
# 3 출력
+
연산자를 활용해서 서로 다른 리스트를 더할 수 있다.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]
x = list()
print(dir(x))
# append, clear, copy, count 등 리스트에 사용할 수 있는 메소드들을 볼 수 있다.
friends = list()
friends.append('Joseph')
friends.append('Glenn')
friends.append('Sally')
print(friends) # ['Joseph', 'Glenn', 'Sally']
friends.sort()
print(friends) # ['Glenn', 'Joseph', 'Sally']
print('Glenn' in friends) # True 출력
문자열과 리스트는 잘 어울려 사용된다.
abc = 'With three words'
stuff = abc.split()
print(stuff) # ['With', 'three', 'words'] 로 출력
words2 = 'first;second;third'
stuff2 = words2.split() # 공백을 기준으로 분할해라!
print(stuff2) # ['first;second;third'] 출력
stuff2 = words2.split(';') # ; 를 기준으로 분할해라!
print(stuff2) # ['first', 'second', 'third'] 출력
line = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
words = line.split() # 해당 라인을 공백을 구분으로 하여 리스트로 저장
print(words[1]) # stephen.marquard@uct.ac.za이 출력
email = words[1] # 추출한 words[1]를 email변수에 저장
address = email.split('@') # @를 구분자로 저장
print(address) # ['stephen.marquard', 'uct.ac.za'] 출력
print(address[0]) # stephen.marquard 출력
print(address[1]) # uct.ac.za 출력