udem.py - (8) Lists

Gomi_kery·2022년 9월 8일
0

udem.py

목록 보기
9/28
post-thumbnail

List

  • 다양한 객체 유형을 포함할 수 있는, 순서가 정해진 시퀀스.
  • [1,2,3,4,5] 양식을 사용.
  • len 함수를 사용하면 리스트 내에 들어있는 요소 수 확인 가능.
animal_list=["cat", "dog", "bird","tiger"]

len(animal_list) 
> 4
  • indexing과 slicing 모두 사용 가능.
animal_list = ["cat","dog","bird","tiger"]

animal_list[3]
> ['tiger']

animal_list[1::]
> ['dog', 'bird', 'tiger']
  • '+' 를 사용해서 문자열 이어 붙이기도 가능하다.
animal_list = ["cat","dog","bird"]
new_list = ["lion","tiger"]

animal_list + new_list
> ['cat', 'dog', 'bird', 'lion', 'tiger']
  • 문자열과 달리 요소의 값을 변경할 수 있음.
animal_list = ["cat","dog","tiger","bird"]
animal_list[3] = "lion" # 3번 인덱싱에 해당하는 요소를 lion으로 변경

animal_list
> animal_list = ["cat","dog","tiger","lion"]

Method

jupiter notebook에서 나오는 메소드만 정리

.append()

  • list의 끝에 요소 삽입.
animal_list = ["cat","dog","tiger","bird"]
animal_list.append("lion")

animal_list
> ["cat","dog","tiger","bird", "lion"]

.pop()

  • list의 마지막 요소 출력 후 삭제.
  • () 안에 인덱스 입력 시 인덱스 위치의 요소 삭제 가능.
animal_list = ["cat","dog","tiger","bird"]

animal_list.pop()
> 'bird'				# 마지막 요소인 bird가 출력됨.
animal_list
> ["cat","dog","tiger"]	

.reserve()

  • list 내 요소를 역순으로 출력
animal_list = ["cat","dog","tiger","bird"]
animal_list.reserve()

animal_list
> ['bird', 'tiger', 'dog', 'cat']

.sort()

  • list 내 요소를 오름차순으로 정렬.
animal_list = ["cat","dog","tiger","bird"]
animal_list.sort()

animal_list
> ['bird', 'cat', 'dog', 'tiger']
  • 다만 메서드의 결과는 저장할 수 없음.
new_list = animal_list.sort()

new_list
> 				# 결과가 출력되지 않음.

# new_list에 결과가 출력되게 하려면
animal_list.sort() 			# 를 실행한 뒤 
new_list = animal_list		# new의 값이 animal과 같다고 선언하면

new_list					# sort된 animal의 결과가 new 호출 시 출력
> ['bird', 'cat', 'dog', 'tiger'] 

.clear()

  • list의 요소 모두 삭제.
animal_list = ["cat","dog","tiger","bird"]
animal_list.clear()

animal_list
> []

.insert()

  • list 내 특성 위치에 요소 삽입.
animal_list = ["cat","dog","tiger","bird"]
animal_list.insert(0,"animal kinds :") # 0번 인덱싱 위치에 "문자열" 삽입

animal_list
> ["animal kinds :","cat","dog","tiger","bird"]

.count()

  • list 내 특정 요소의 갯수 출력
animal_list = ["cat","dog","cat","bird"]

animal_list.count("cat")
> 2
animal_list.count("lion")
> 0

.copy()

  • list 내의 요소를 모두 복사
animal_list = ["cat","dog","tiger","bird"]
backup_list = animal_list.copy()

backup_list
> ["cat","dog","tiger","bird"]

.remove()

  • list 내 특정 요소 삭제
animal_list = ["cat","dog","tiger","bird"]
animal_list.remove("dog")

animal_list
> ['cat', 'tiger', 'bird']
profile
QA. 손으로 할 수 있는 모든 것을 좋아합니다.

0개의 댓글