728x90

list는 많이 쓰이는 문법입니다.
파이썬에서의 리스트(list)는 원소들이연속적으로 저장되는 형태의 자료형인데요.
자바에서는 <T>의 제네릭이 타입을 맞춰주기도 했지만 모두 같은 타입일 필요는 없습니다.
리스트는 대괄호([, ])로 감싸진 형태이며 0개 이상의 데이터가 저장됩니다.
a = list()
print(a)

생성자를 통해 리스트를 생성하고 출력해 보았습니다.
아무 값도 넣지 않았기때문에 []만 출력이 됩니다!
a.append(1)
print(a)

append를 통해 1의 값을 넣은뒤 출력하면 1의 값이 나옵니다
a.append('one')
print(a)

같은 타입이 아니여도 값을 넣을수 있으며 새롭게 값을 넣으면 용량이 늘어납니다!
a[1] = 'two'
print(a)

들어가 있는 값을 바꿀수 있습니다!
# a[2] = 3
# print(a)

제가 지금은 주석처리를 해놓았는데요! 현재 a는 1번지까지밖에 존재하지 않습니다.
그런데 2번지에 값을 대입하려 한다면 에러가 발생합니다.
b = [1, 2, 3, 4, 5]
print(b)

list() 함수를 사용하지 않고 대괄호([, ])를 이용하여 list를 생성할수 있습니다.
print(b[0] + b[4])

타입이 같다면 연산도 할수 있습니다.
b.reverse()
print(b)

reverse 함수를 이용해 역순으로 출력할수 있습니다
다만 타입이 다른 데이터가 저장되어있다면 에러가 발생합니다.
b.sort()
print(b)

위의 배열은 이미 정렬이 되어있지만 sort함수를 사용해서 순서대로 정렬도 가능합니다.
c = ['a', 'b', 'c', ['d', 'e', 'f']]
print(c)

리스트는 리스트안에 리스트를 넣을수도 있습니다.
또한 f를 출력하고자 한다면 c[3][2]를 출력해야합니다.
print(b + c)

리스트 끼리의 연산도 가능합니다.
728x90
'Python > Python' 카테고리의 다른 글
[Python] set(집합) (0) | 2022.04.29 |
---|---|
[Python] tuple(튜플), unpacking (0) | 2022.04.28 |
[Python] 문자열(string) (0) | 2022.04.26 |
[Python] 숫자형(number) 타입 (0) | 2022.04.25 |
[Python] 변수(variable)와 타입(type) (0) | 2022.04.24 |