728x90
728x90

1. 리스트

데이터들을 하나의 묶음으로 나열한 것 (점심메뉴 리스트)

 

기본형

lunch=["샤브샤브", "물냉면", "케밥", "불고기", "연어덮밥", "돈가스"]
# 인덱스 0 , 1, ...

 

예제

attendance=["김", "이", "박", 1, 1, 2, 2, True, 1==5, 2+2]
print(attendance);
print(attendance[2]);
print(attendance[-1]); 

#['김', '이', '박', 1, 1, 2, 2, True, False, 4]
#박
#4 뒤에서부터 센다

 

리스트 길이 측정 / 데이터 타입 확인 / 범위 지정으로 특정 인덱스 추출

list_=["홍", "윤", "이", "임"]
print(len(list_)) #리스트 길이 측정
print(type(list_)) #데이터 타입 확인
print(list_[1:2]) #시작부터 끝 인덱스 직전까지 출력
print(list_[:2]) #처음부터 인덱스 직전까지 출력

#4
#<class 'list'>
#['윤']
#['홍', '윤']

 

리스트 값 변경

bird_list=["딱따구리", "까치", "부엉이"]
bird_list[1]="참새"
print(bird_list) #['딱따구리', '참새', '부엉이']

 

리스트 값 삽입, 추가 (insert, append)

 

animal=["dog", "cat", "turtle", "lion"]
animal.insert(0, "bear")
print(animal) #['bear', 'dog', 'cat', 'turtle', 'lion']
animal.append("tiger")
print(animal) #['bear', 'dog', 'cat', 'turtle', 'lion', 'tiger']

 

extend() : 리스트에 배열 추가
animal=["dog", "cat", "turtle", "lion"]
bird=["독수리", "부엉이", "참새"]
animal.extend(bird) #넓히다, 확장하다
print(animal) #['dog', 'cat', 'turtle', 'lion', '독수리', '부엉이', '참새']

 

extend와 append 차이점 예제

animal=["dog", "cat", "turtle", "lion"]
bird=["독수리", "부엉이", "참새"]
animal.append(bird) #리스트 자체가 4번째 요소로 들어감
print(animal) #['dog', 'cat', 'turtle', 'lion', ['독수리', '부엉이', '참새']]

 

리스트 연산

animal=["dog", "cat", "turtle", "lion"]
bird=["독수리", "부엉이", "참새"]
 
print(animal+bird) #['dog', 'cat', 'turtle', 'lion', '독수리', '부엉이', '참새']

 

리스트 제거

animal=["dog", "cat", "turtle", "lion"]
bird=["독수리", "부엉이", "참새"]

animal.remove("lion")
animal.pop(0)
animal.pop() #가장 마지막 인덱스 요소가 사라진다.
print(animal)
animal=["dog", "cat", "turtle", "lion"]
bird=["독수리", "부엉이", "참새"]
del animal[2]
#del animal #전체가 삭제되어 error
print(animal) #['dog', 'cat', 'lion']

 

clear() : 리스트 비우기
animal=["dog", "cat", "turtle", "lion"]
bird=["독수리", "부엉이", "참새"]
animal.clear()
print(animal) #[]

 

sort() : 리스트 정렬
eng=["b", "a", "d", "c", "e"]
num=[4,5,600,-4,0]

eng.sort()
#eng.sort(reverse=True) 오름차순으로 정렬
#eng.sort(reverse=False) 내림차순으로 정렬
num.sort()

print(eng)
print(num)

#['a', 'b', 'c', 'd', 'e']
#[-4, 0, 4, 5, 600]

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v