리스트 & 튜플

mong·2022년 10월 8일
0

Python Study

목록 보기
2/2
post-thumbnail

List

  • list의 item은 0부터 시작
  • 중복 허용
# 중복 허용
mylist = ['apple', 'banana', 'orange', 'apple']
print(list)

> ['apple', 'banana', 'orange', 'apple']


# list 길이 출력
## len 함수
print(len(mylist))

> 3

List Items - Data Types

  • 숫자, 문자, boolen
  • 혼합도 가능
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list3 = [True, False]
list4 = ['a', 12, True]

# type() 함수
# 타입 확인
print(type(list4))

> <class 'list'>

The list() Constructor

  • (()) 주의! 괄호가 2개!
# (())
mylist = list(('a', 'b', 'c'))
print(mylist)

> ['a', 'b', 'c']

Access Items

  • index 접근
# 0 1 2
print(mylist[1])
> b

# -3 -2 -1
print(mylist[-1]) # -1 은 뒤에서부터 첫번째
> c
  • list slicing
    • positive indexes -1
    • negative indexes -2
# list slicing [n:m]
# n부터 m-1까지 
#        0     1      2        3         4       5
list1 = ['a', 'ab', 'apple', 'orange', 'kiwi', 'lemon']
print(list1[2:5])  # 2 3 4

> ['apple', 'orange', 'kiwi']


# [:m]
# 0 ~ m-1
print(list1[:4])  # 0 1 2 3

> ['a', 'ab', 'apple', 'orange']


# [n:]
# n ~ 끝
print(list1[2:]) # 2 3 4 5

> ['apple', 'orange', 'kiwi', 'lemon']
# list slicing [-n:-m]
# 뒤에서 n번째부터 m+1번째까지
#        -6    -5     -4        -3       -2      -1
list1 = ['a', 'ab', 'apple', 'orange', 'kiwi', 'lemon']
print(list1[-4: -1]) # -4 ~ -2 까지

> ['apple', 'orange', 'kiwi']

Check if Item Exists

if 'lemon' in list1:
	print('yes')

> yes

Change List Items

# index 지정해서 새로운 값으로 change
mylist = ['apple', 'banana', 'orange']
mylist[1] = 'blueberry'
print(mylist)

> ['apple', 'blueberry', 'orange']


# slicing으로 값 add & change
mylist[1:2] = ['banana', 'lemon']   # index 1을 banana로 수정
print(mylist)                       # banana 뒤에 lemon 추가

> ['apple', 'banana', 'lemon', 'orange']


# slicing으로 여러 개의 값 한번에 change
thelist = ['apple', 'banana', 'orange', 'kiwi', 'lemon']
thelist[1:3] = ['wow', 'gum']   # index 1,2의 값을 change
print(thelist)

> ['apple', 'wow', 'gum', 'kiwi', 'lemon']

Add List Items

  • append()
    • 맨 뒤에 추가
  • insert()
    • index 지정
    • 해당 index에 추가
  • extend()
    • list 이어 붙이기
# append(추가할 값)
list1 = ['a', 'b', 'c']
list1.append('d')
print(list1)

> ['a', 'b', 'c', 'd']


# insert(index, 추가할 값)
list1.insert(1, 'lemon')   # index 1 위치에 lemon 추가
print(list1)               # 뒤의 index들은 index 밀림

> ['a', 'lemon', 'b', 'c', 'd']


# extend(뒤에 추가할 list)
list2 = ['berry', 'apple', 'melon']
list1.extend(list2)        # list1 뒤에 add list2
print(list1)

> ['a', 'lemon', 'b', 'c', 'd', 'berry', 'apple', 'melon']

Remove List Items

  • remove()
    • 삭제할 값 지정
  • pop()
    • 삭제할 index 지정
    • index 지정 x → last index 값 삭제
    • stack 형태
  • del
    • 특정 index 지정
    • index 지정 x → list 자체를 delete
  • clear()
    • list 내부의 값들을 clear
    • list는 남아 있음!! 내용만 없어짐. # del 차이점
# remove()
list1.remove('d')
print(list1)

> ['a', 'lemon', 'b', 'c', 'berry', 'apple', 'melon']  # d 삭제됨


# pop()
list1.pop(1)  # index 1 삭제
print(list1)

>  ['a', 'b', 'c', 'berry', 'apple', 'melon']  # lemon 삭제됨

list1.pop()   # 마지막 index 삭제
print(list1)

> ['a', 'b', 'c', 'berry', 'apple']  # melon 삭제됨


# del
# 내장함수 x
del list1[0]  # index 0 삭제
print(list1)

>  ['b', 'c', 'berry', 'apple']   # a 삭제됨

del list1       # list1 삭제
print(list1)    # ERROR!!! list1 자체를 지워서 list1 존재하지 않음! 
                # NameError: name 'list1' is not defined


# clear()
list1 = ['a', 'b']
list1.clear()
print(list1)

> []    # 비어 있음

List Comprehension

fruits = ['apple', 'banana', 'kiwi', 'orange', 'melon']
newlist = []

for x in fruits:            # fruits에 있는 값들 중
	if 'a' in x:            # a가 들어간 단어는
		newlist.append(x)   # newlist에 추가

print(newlist)

> ['apple', 'banana', 'orange']


# 위에 코드 간단하게 한 줄로 사용하기
fruits = ['apple', 'banana', 'kiwi', 'orange', 'melon']
newlist = [x for x in fruits if 'a' in x]
print(newlist)

> ['apple', 'banana', 'orange']
# condition 비교
List = [x for x in fruits if x != 'apple']  # apple이 아닌 값만 추가
print(List)

> ['banana', 'kiwi', 'orange', 'melon']
# iterable하게 list를 추가
list1 = [x for x in range(10)]  # 0 ~ 9까지 추가
print(list1)

> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Sort Lists

# sort()
# 오름차순 정렬
fruits = ['apple', 'kiwi', 'orange', 'melon', 'banana']
fruits.sort()
print(fruits)

> ['apple', 'banana', 'kiwi', 'melon', 'orange']


# sort(reverse=True)
# 내림차순 정렬
fruits = ['apple', 'kiwi', 'orange', 'melon', 'banana']
fruits.sort(reverse=True) 
print(fruits)

> ['orange', 'melon', 'kiwi', 'banana', 'apple']

Copy Lists

  • copy()
    • 리스트 내용 복제
# copy()
fruits = ['apple', 'kiwi', 'orange', 'melon', 'banana']
list1 = fruits.copy()
print(list1)

> ['apple', 'kiwi', 'orange', 'melon', 'banana']

Join Two Lists

fruits = ['apple', 'kiwi', 'orange', 'melon', 'banana']
list2 = [1, 2, 3]

list3 = list2 + fruits
print(list3)

> [1, 2, 3, 'apple', 'kiwi', 'orange', 'melon', 'banana']



Tuple

  • list와 굉장히 유사
  • list와의 차이점
    • 소괄호를 사용함 → list: [], tuple: ()
    • change-up X → 수정이 안 됨!!!
  • 공통점
    • container형(box형) 변수
    • index로 특정 요소 access
    • iterable → for 문으로 돌릴 수 있음
  • 장점
    • iteration (for문을 돌릴 때) 속도가 list보다 훨씬 빠름
mytuple = ['apple', 'banana', 'orange']

mytuple[1] = 'abc'  # ERROR!!! 값 수정 불가능!
					# TypeError: 'tuple' object does not support item assignment

0개의 댓글