본문 바로가기

IT/Python

[파이썬] List 관련 (Python)

- List에서 데이터 추가 기능은 아래와 같다

sample_list = [1, 1, 2]

print("sample_list before: ", sample_list)

sample_list.append(3)

#List에데이터추가기능

print("sample_list after: ", sample_list)

[1, 1, 2]>> [1,1,2,3]

- 데이터를 대체도 가능

party_list = ["Joana", "Alton", "Tobias"]

print("party_list before: ", party_list)

# the list after Insert

party_list[1] = "Colette"

print("party_list after: ", party_list)

["Joana", "Alton", "Tobias"] >> ['Joana', 'Colette', 'Tobias']

- 데이터를 Overwriting도 가능하다

party_list = ["Joana", "Alton", "Tobias"]

print("before:",party_list)

party_list[1] = party_list[1] + " Derosa"

print("\nafter:", party_list)

["Joana", "Alton", "Tobias"] >> ['Joana', 'Alton Derosa', 'Tobias']

- 데이터 Add도 가능 (append는 그냥 추가라면, add는 몇 번째 데이터에 이 값을 추가 라는 의미)

party_list = ["Joana", "Alton", "Tobias"]

print("party_list before: ", party_list)

party_list.insert(1,"Colette")

print("party_list after: ", party_list)

print("index 1 is", party_list[1], "\nindex 2 is", party_list[2], "\nindex 3 is", party_list[3])

>>

party_list before: ['Joana', 'Alton', 'Tobias']

party_list after: ['Joana', 'Colette', 'Alton', 'Tobias']

index 1 is Colette

index 2 is Alton

index 3 is Tobias

- 지우는 건 아래와 같다.

sample_list = [11, 21, 13, 14, 51, 161, 117, 181]

print("sample_list before: ", sample_list)

del sample_list[-1]

#리스트에서제일마지막데이터를지워라

print("sample_list after: ", sample_list)

sample_list before: [11, 21, 13, 14, 51, 161, 117, 181]

sample_list after: [11, 21, 13, 14, 51, 161, 117]

- .pop() 를 사용해서 데이터를 뽑아낼 수 도 있다.

number_list = [11, 21, 13, 14, 51, 161, 117, 181]

print("list before:", number_list)

num_1 = number_list.pop()

#제일마지막숫자를뽑아서num_1

num_2 = number_list.pop()

#남은list에서제일마지막숫자를num_2

print("list after :", number_list)

print("add the popped values:", num_1, "+", num_2, "=", num_1 + num_2)

>>

list before: [11, 21, 13, 14, 51, 161, 117, 181]

list after : [11, 21, 13, 14, 51, 161]

add the popped values: 181 + 117 = 298

- .remove()를 통하여 정확한 "" data를 제거할 수 있다.

dogs = ["Lab", "Pug", "Poodle", "Poodle", "Pug", "Poodle"]

print(dogs)

while "Poodle" in dogs:

dogs.remove("Poodle")

print(dogs)

>>

['Lab', 'Pug', 'Poodle', 'Poodle', 'Pug', 'Poodle']

['Lab', 'Pug', 'Poodle', 'Pug', 'Poodle']

['Lab', 'Pug', 'Pug', 'Poodle']

['Lab', 'Pug', 'Pug']

'IT > Python' 카테고리의 다른 글

[파이썬] List 관련2 (extend, reverse, sort)  (0) 2020.06.29
[파이썬] range 구문  (0) 2020.06.29
[파이썬] Slicing (자르기)  (0) 2020.06.29
[파이썬] Casting/캐스팅  (0) 2020.06.29
[파이썬] if, elif, else 구문  (1) 2020.06.29