[Python] List of major destructive methods of list operation (addition / deletion / sorting)

[Python] List of major destructive methods of list operation (addition / deletion / sorting)

A list of major destructive methods (overwriting the original data).

** **

  1. [insert](#insert method)
  2. [append](#append method)
  3. [extend](#extend method)
  4. [Add by slice](#Add by slice)
  5. [Add element](#Add element)
  6. Replace

** ** 5. [remove](#remove method) 6. [pop](#pop method) 7. [clear](#clear method) 8. [del statement](#del statement)

  1. [Delete by specifying index number](#Delete by specifying index number)
  2. [Delete by specifying a range](#Delete by specifying a range)
  3. [Delete All](#Delete All)

** ** 9. [sort](#sort method)

  1. [Ascending sort](# Ascending sort)
  2. [Descending Sort](#Descending Sort)
  3. [reverse](#reverse method)

** ** 11. [Notes on destructive methods](#Notes on destructive methods) 12. [Destructive method example](# Destructive method example)


## insert method Insert the value by specifying the index number.

insert x y └ Insert y at index number x. └ x is an integer └ If you specify an index number above (or below) the original element, it will be added to the end (beginning).

python


a = [1,2,3]

#Add "10" to 0th
a.insert(0,10)
print(a)

#output
[10, 1, 2, 3]

** ▼ If you specify an index number that does not exist **

python


a = [1,2,3]

#Added "20" to the 10th
a.insert(10,20)
print(a)

#output
[1, 2, 3, 20]

Although index number 10 is specified, it is added to the end because the maximum of the target list is less than 10.

** ▼ When a non-existent index number is specified (minus) **

python


a = [1,2,3]

#-Added "30" to the 10th
a.insert(-10,30)
print(a)

#output
[30, 1, 2, 3]

## append method Add an element at the end. (Add as a lump)

ʻAppend (value to add)`

python


a=[1,2,3]

a.append('a')
print(a)

##output
[1, 2, 3, 'a']

** ▼ Character strings and arrays are entered as chunks. (* Difference from extend) **

String


a=[1,2,3]

a.append("abcde")
print(a)

##output
[1, 2, 3, 'abcde']

list


a=[1,2,3]
b=[4,5,6]

a.append(b)
print(a)

##output
[1, 2, 3, [4, 5, 6]]

** ▼ I can't add myself (* Difference from extend) **

list


a=[1,2,3]

a.append(a)
print(a)

#output
[1, 2, 3, [...]]

** ▼ When the parent object is one-dimensionally larger **

list


a=[[1,2,3]]
b=[4,5,6]

a.append(b)
print(a)

#output
[[1, 2, 3], [4, 5, 6]]

It becomes the same dimension.


## extend method Add an element at the end. (Add one character at a time)

ʻExtend (element to add)` └ Add one character at a time └ Strings are decomposed

1D list


a=[1,2,3]
b=[4,5,6]

a.extend(b)
print(a)

#output
[1, 2, 3, 4, 5, 6]

String


a=[1,2,3]

a.extend("abcde")
print(a)

#output
[1, 2, 3, 'a', 'b', 'c', 'd', 'e']

** ▼ You can add yourself (* difference from append) **

python


a=[1,2,3]

a.extend(a)
print(a)

#output
[1, 2, 3, 1, 2, 3]

** ▼ Combine in chunks for multidimensional **

python


a=[1,2,3]
b=[[4,5,6],[7,8,9]]

a.extend(b)
print(a)

#output
[1, 2, 3, [4, 5, 6], [7, 8, 9]]

Two dimensions


a=[[1,2,3]]
b=[[4,5,6],[7,8,9]]

a.extend(b)
print(a)

#output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

## Add with slice Although it is not a method, it is also possible to specify a range with a slice and insert it.

■ Properties that have both extend and append ・ Add to the same level ・ Add in chunks (do not decompose character by character)

Add element

list [x: x] = element to add └ x: Index number you want to add └ Specify the same range for the slice range * If they are different, replacement will occur.

Index number 1 is "'aaa','bbb'"Add


a=[1,2,3]

a[1:1]=['aaa','bbb']
print(a)

#output
[1, 'aaa', 'bbb', 2, 3]

** ▼ Negative index number can be specified **

minus


a=[1,2,3]

a[-1:-1]=['aaa','bbb']
print(a)

#output
[1, 2, 'aaa', 'bbb', 3]

From the last element, it becomes 0, -1, -2 ,,,.


** ▼ Designation outside the range ** ・ If it is larger on the plus side, add it at the end. ・ If it is large on the minus side, add it at the beginning.

Out of the plus range


a=[1,2,3]

a[10:10]=['aaa','bbb']
print(a)

#output
[1, 2, 3, 'aaa', 'bbb']

Outside the negative range


a=[1,2,3]

a[-10:-10]=['aaa','bbb']
print(a)

#output
['aaa', 'bbb', 1, 2, 3]

Replace

list [x: y] = element to add └ Replace the range from x to y-1. └ y is not included

** ▼ Replace nth element ** list[n:n+1]

Replacement of index number 2


a=[1,2,3,4,5,6,7]

a[2:3]=['aaa','bbb']
print(a)

##output
[1, 2, 'aaa', 'bbb', 4, 5, 6, 7]

** ▼ Replace all together **

Replace all at once


a=[1,2,3,4,5,6,7]

a[0:5]=['aaa','bbb']
print(a)

##output
['aaa', 'bbb', 6, 7]

Replace 0-4th range.


** ▼ When out of range is specified **

python


a=[1,2,3,4,5,6,7]

a[0:10]=['aaa','bbb']
print(a)

#output
['aaa', 'bbb']

** ▼ When out of range is specified 2 **

python


a=[1,2,3,4,5,6,7]

a[10:20]=['aaa','bbb']
print(a)

#output
[1, 2, 3, 4, 5, 6, 7, 'aaa', 'bbb']

** ▼ Replace all **

python


a=[1,2,3,4,5,6,7]

a[:]=['aaa','bbb']
print(a)

#output
['aaa', 'bbb']

## remove method Specify a value to remove the first element.

remove (element to remove) └ If there are multiple, ** only the first element ** deleted └ Non-existent value is an error

python


a = [1,2,3]

a.remove(1)
print(a)

#output
[2, 3]

** ▼ When there are multiple specified values **

python


a = [1,2,3,1,2,3,1,2,3]

a.remove(2)
print(a)

#output
[1, 3, 1, 2, 3, 1, 2, 3]

Delete only the first element.


## pop method Delete by specifying the index number.

pop (index number) └ Delete the value of the corresponding index number └ Numbers outside the range are errors

python


a = [1,2,3]

a.pop(2)
print(a)

#output
[1, 2]

Deleted index number 2 (value 3).

▼ Error outside the range

python


a = [1,2,3]

a.pop(-10)
print(a)

#output
IndexError: pop index out of range

## clear method `clear()` └ Bracket required └ No argument * Error if there is an argument

python


a = [1,2,3]

a.clear()
print(a)

##output
[]

All the contents disappear. The container (variable) remains.

del statement

Although it is not a method for list, elements can be deleted with a del statement.

del list object [index number] └ Index number specified by slice

▼ Delete by specifying the index number

python


a=[1,2,3]

del a[0]
print(a)

##output
[2, 3]

Same as pop method.

▼ Delete by specifying a range

[Start value: End value] └ The end value is not deleted. (Less than)

Number 3~Remove 4 (5 not included)


b=[1,2,3,4,5,6,7,8,9]

del b[3:5]
print(b)

##output
[1, 2, 3, 6, 7, 8, 9]

▼ Delete all

Specify the entire range [:] in the slice.

python


a=[1,2,3]

del a[:]
print(a)

##output
[]

Same as the clear method.


## sort method

Ascending sort

sort() └ Default (reverse = False) └ No argument required * Error if entered

Ascending sort


a=[4,2,10,-10]

a.sort()
print(a)

##output
[-10, 2, 4, 10]

Alphabet


a=[]
a.extend("egkacb")

a.sort()
print(a)

##output
['a', 'b', 'c', 'e', 'g', 'k']

Descending sort

sort(reverse=True) └ Specify "reverse = True" as an option

Descending sort


a=[4,2,10,-10]

a.sort(reverse=True)
print(a)

##output
[10, 4, 2, -10]

## reverse method Invert the elements of list. * Different from descending sort

Numerical inversion


a=[4,2,10,-10]

a.reverse()
print(a)

##output
[-10, 10, 2, 4]

Alphabet inversion


a=[]
a.extend("egkacb")

a.sort()
print(a)

##output
['b', 'c', 'a', 'k', 'g', 'e']

## Precautions for destructive methods ** Cannot be assigned to a variable. ** **

Because you are modifying the original object. For example -A.append () refers to "a" itself. -There is no such thing as "a.append ()".

not exist


a = [1,2,3]

b = a.append(4)
print(b)

##output
None

Since the non-existent one is assigned to the variable b, the content of b is None.

If you want to add more elements, play with a itself again.


## Destructive method example

▼ Question When any of insert, print, remove, append, sort, pop, reverse is input, the corresponding process is executed.

--insert a b: Insert the value b at index number a. --remove a: Remove the first value a. --append a: Append the value a at the end. --pop a: Delete the value of index number a --sort: Ascending sort. --reverse: reverse list --print: Output

URL

▼sample input

python


12 #Number of commands to enter
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

▼sample output

python


[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

▼answer1

python


if __name__ == '__main__':
    n = int(input())
    lists = [input() for _ in range(n)]

    arr=[]
    for i in lists:
        arr.append(i.split())
    
    res=[]
    for j in arr:
        
        if len(j) >= 2:
            a=int(j[1])
        
        if len(j) >=3:
            b=int(j[2])
        
        #Each process
        if j[0]=="insert":
            res.insert(a, b)
        
        if j[0]=="print":
            print(res)
            
        if j[0]=="remove":
            res.remove(a)
            
        if j[0]=="append":
            res.append(a)
            
        if j[0]=="sort":
            res.sort()
            
        if j[0]=="reverse":
            res.reverse()
            
        if j[0]=="pop":
            res.pop()
ans=res

▼answer2 (with eval method)

python


n = int(input())
l = []
for _ in range(n):
    s = input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        #Create an argument part with a string and combine it with cmd
        cmd += "("+ ",".join(args) +")"
        
        #Execute expression (character string in parentheses)
        eval("l."+cmd)
    else:
        print (l)

・ ʻEval ("expression") ` └ Put an expression in the argument * Not a statement

Executes the expression of the string given as an argument. -Example: eval ("list.insert (2,5)")


Recommended Posts

[Python] List of major destructive methods of list operation (addition / deletion / sorting)
Basic operation list of Python3 list, tuple, dictionary, set
[Python] Operation of enumerate
List of python modules
Python: Get a list of methods for an object
Summary of Python3 list operations
Operation of filter (None, list)
[Python] Operation memo of pandas DataFrame
About the basics list of Python basics
[Introduction to Udemy Python3 + Application] 18. List methods
Python basic operation 1st: List comprehension notation
[Introduction to Udemy Python3 + Application] 17. List operation
[python] Get a list of instance variables
Basic grammar of Python3 series (list, tuple)
Summary of how to use Python list
[Python] Get a list of folders only
A memorandum of python string deletion process