We are advancing Python learning according to Learning Roadmap for Python Beginners on Tommy's blog. This time, I will deal with the latter half of [Introduction to Python] Summary of how to use list (Part 1).
--Those who are studying on Tomi-san's blog --For those who want to get an overview of how to use list
Google Colaboratory
Use ** Add Method ** to add data to the list
Because these are methods
List variable.append()
I use it.
list_a = [1, 2, 3, 4] #1,2,3,4 list_a list_a.append(5) #list_Add 5 to A at the end print(list_a)
#### **`Execution result`**
```text
[1, 2, 3, 4, 5] #5 was added last.
list_a = [1,2,3,4]
list_b = [5,6]
list_a.append(list_b)
print(list_a)
Execution result
[1, 2, 3, 4, [5, 6]] #Since append is added as it is[]Will also be added
list_a = [1,2,3,4]
list_b = [5,6]
list_a.extend(list_b) #Let's use extend
print(list_a)
Execution result
[1, 2, 3, 4, 5, 6] #Only the numbers were matched!!
list_a = [1,2,3,4]
list_a.extend(5)
Execution result
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-25c1d760cd29> in <module>()
1 #Note: Since extend is a combination of lists, create a list and use it.
2 list_a = [1,2,3,4]
----> 3 list_a.extend(5)
TypeError: 'int' object is not iterable
Will result in an error
list_a = [1, 2, 3, 4]
list_b = [5, 6]
list_a.insert(1, list_b) #Element No.List to 1_b[5, 6]Add
print(list_a)
Execution result
[1, [5, 6], 2, 3, 4] #Added and printed
list_a = [1, 2, 3, 4]
list_b = [5]
list_a.insert(0, list_b)
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(1, list_b)
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(2, list_b)
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(3, list_b)
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(4, list_b)
print(list_a)
Execution result
[[5], 1, 2, 3, 4] #Element No. 0
[1, [5], 2, 3, 4] #Element No. 1
[1, 2, [5], 3, 4] #Element No. 2
[1, 2, 3, [5], 4] #Element No. 3
[1, 2, 3, 4, [5]] #Element No. 4
This is OK. Then what is this?
list_a = [1, 2, 3, 4]
list_b = [5]
list_a.insert(-4, list_b) #Element No. -4
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(-3, list_b) #Element No. -3
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(-2, list_b) #Element No. -2
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(-1, list_b) #Element No. -1
print(list_a)
list_a = [1, 2, 3, 4]
list_a.insert(0, list_b) #Element No. 0
print(list_a)
Execution result
[[5], 1, 2, 3, 4] #Element No. -4
[1, [5], 2, 3, 4] #Element No. -3
[1, 2, [5], 3, 4] #Element No. -2
[1, 2, 3, [5], 4] #Element No. -1 Doesn't it come to the end of the element? that?
[[5], 1, 2, 3, 4] #Element No. 0
I'm not sure right now ...
Next time, I plan to delete clear, pop, remove, del.
[Introduction to Python] Summary of how to use list (Part 1)
Recommended Posts