03. Python Basics - Sequence Types(list, tuple, range)

Jayson Hwang·2022년 4월 5일
0

Python Basics

목록 보기
3/10

3. Sequence Types

list(리스트), tuple(튜플), range

<<<list>>>
  mylist = ["apple", "banana", "cherry"]
  print(mylist) # ['apple', 'banana', 'cherry']
  
<<<tuple>>>
  mytuple = ("apple", "banana", "cherry")
  print(mytuple) # ('apple', 'banana', 'cherry')

3-(1) list(리스트)

순서를 따지는 객체의 집합

List items are ordered, changeable, and allow duplicate values.

  • Ordered:
    it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.
  • Changeable:
    The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
  • Allow Duplicates:
    Since lists are indexed, lists can have items with the same value,
    thislist = ["apple", "banana", "cherry", "apple", "cherry"]
  • 다양한 데이터 타입의 값을 함께 가질 수 있으며, 리스트 안에 리스트를 요소로 갖거나, 토플, 딕셔너리 등을 갖는 등 데이터의 요소에 중복이 가능하다.
    cmpx_list = [8, "i", 3.1, [55, 89], complex(3-2j)]

3-(1.1) 리스트 선언

대괄호[ ] 사이에 값을 넣어 표현하고, 각 요소 사이에는 콤마(,)를 넣어 구분

  mylist = ["apple", "banana", "cherry"]
  mylist = []
  mylist = [1, 2, 3, 4, 5]
  mylist = [1, "apple", 2]

3-(1.2) 리스트 인덱싱(indexing)

mylist = [1, 2, 3, 4, 5]
print(mylist) # [1, 2, 3, 4, 5]
print(mylist[0]) # 1
print(mylist[0] + mylist[-1]) # 6

mylist = ["apple", "banana", "cherry"]
print(mylist.index("banana")) # 1

3-(1.3) 리스트 처리함수

▶︎ 리스트 값 수정
	a = [1, 2, 3]
    a[2] = 4 # 2번째 자리를 4로 바꿈
    print(a) # [1, 2, 4]
▶︎ 리스트 값 추가(append)
	mylist = ["apple", "banana", "cherry"]
    mylist.append("orange")
    print(mylist) # ["apple", "banana", "cherry", "orange"]
    
    num_list = [1, 2, 3]
    num_list.append([4, 5, 6])
    print(num_list) # [1, 2, 3, [4, 5, 6]]
    
▶︎ 확장(extend)
	num_list = [1, 2, 3]
    num_list.extend([4, 5, 6])
    print(num_list) # [1, 2, 3, 4, 5, 6]
▶︎ 리스트 요소 삽입(insert) #.insert(index, object)
	num_list = [1, 2, 3]
    num_list.insert(0, 5) # 0번째 자리에 5를 넣어줌
    print(num_list) # [5, 1, 2, 3]
▶︎ 리스트 요소 제거(remove) : 첫번째로 나오는 요소를 삭제
	num_list = [1, 2, 3, 2, 1]
    num_list.remove(2) # 리스트에서 첫번째로 나오는 2를 삭제
    print(num_list) # [1, 3, 2, 1]
▶︎ 리스트 모두 제거(clear)
	num_list = [1, 2, 3, 4, 5]
    num_list.clear()
    print(num_list) # []
▶︎ 리스트 요소 끄집어 내기(pop) : 마지막 요소를 꺼내고, 기존 리스트에서 해당 요소 삭제
	num_list = [1, 2, 3]
    
    num_list.pop() # 맨 뒤 요소 1개(3) 끄집어냄
    print(num_list) # [1, 2]
    num_list.pop() # 맨 뒤 요소 1개(2) 끄집어냄
    print(num_list) # [1]
    num_list.pop() # 맨 뒤 요소 1개(1) 끄집어냄
    print(num_list) # []
▶︎ 리스트에 포함된 요소 갯수세기(count)
	num_list = [1, 2, 3, 2, 2, 1]
    print(num_list.count(2)) # 3 -> 리스트에 2가 3개 있음
▶︎ 리스트 정렬(sort)
	num_list = [1, 5, 2, 4, 3]
    num_list.sort()
    print(num_list) # [1, 2, 3, 4, 5]
▶︎ 리스트 뒤집기(reverse)
	mylist = ["apple", "banana", "cherry"]
    mylist.reverse()
    print(mylist) # ["cherry", "banana", "apple"]

3-(2) tuple(튜플)

리스트와 유사하지만 2가지 차이점

  • 리스트는 [ ]로 작성, 튜플은 ( )로 작성
  • 리스트는 값을 수정할 수 있지만, 튜플은 값을 변경할 수 없다.
  • 프로그램이 실행되는 동안 그 값이 변경되지 않는 경우에 튜플을 사용한다.
  • 리스트에 비해 튜플은 더 적은 메모리를 필요로하여, 속도가 빠르다는 장점이 있다.

Tuple items are ordered, unchangeable, and allow duplicate values.

  • Ordered:
    The items have a defined order, and that order will not change.
  • Unchangeable:
    Tuples are unchangeable, meaning that we cannot change, add, and remove items after the tuple has been created.
  • Allow Duplicates:
    Since tuples are indexed, they can have items with the same value,
    thistuple = ("apple", "banana", "cherry", "apple", "cherry")

3-(2.1) 튜플의 요소 값 수정 관련

menu = ("돈까스", "치즈까스")
print(menu[0]) # 돈까스
print(menu[1]) # 치즈까스

menu.append("생선까스") # 튜플에 "생선까스"를 추가
# Error 발생 -> 'tuple' object has no attribute 'append'

예제

당첨자 뽑기 프로그램
총 20명 중에 무작위로 추첨하여 치킨 1, 커피 3명 선별(중복당첨은 불가)

from random import *
users = range(1, 21) #1부터 20까지 숫자를 생성
users = list(users)

shuffle(users)

winners = sample(users, 4) #4명 중에서 1명은 치킨, 3명은 커피

print("-- 당첨자발표 --")
print("치킨 당첨자 : {0}".format(winners[0]))
print("커피 당첨자 : {0}".format(winners[1:]))
print("-- 축하합니다 --")



-- 당첨자발표 --
치킨 당첨자 : 12
커피 당첨자 : [17, 10, 14]
-- 축하합니다 --
profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글