append()

append() function is to add 

a = [1, 2, 3]
a.append(4)                 # add 4
print('a:', a)              # [1, 2, 3, 4]

a.append([5, 6])            # add [5, 6] 
print('a:', a)              # [1, 2, 3, 4, [5, 6]]

index()

It is like indexOf() in Java.

It is different from find()

 

 

pop()

To delete the last one

list = [10, 20, 30, 40, 50]
data1 = list.pop()             
print('data1:', data1)         
print('list:', list)           

data2 = list.pop(2)            
print('data2:', data2)          
print('list:', list)

insert()

a = [1, 2, 3]

# index no.0 -> put '4'
a.insert(0, 4)
print('a:', a)                  # [4, 1, 2, 3]

a.insert(3, 5)
print('a:', a)                  # [4, 1, 2, 5, 3]

sort()

namelist = ['Mary','Sams','Amy','Tom','Mike','Bob','Kelly']

namelist.sort()               # ascending order
print('namelist:', namelist)  

namelist.sort(reverse=True)    # descending order
print('namelist:', namelist)

sorted()

The difference between sort() and sorted() is that if you use sort(), the original list remains unchanged.

namelist = ['Mary','Sams','Amy','Tom','Mike','Bob','Kelly']

result1 = sorted(namelist)                  # ascending order
result2 = sorted(namelist, reverse= True)   # descending order
print(type(result1))                        # <class 'list'>
print(type(result2))

print('result1:', result1)  # ['Aimy', 'Bob', 'Kelly', 'Mary', 'Michale', 'Sams', 'Tom']
print('result2:', result2)  # ['Tom', 'Sams', 'Michale', 'Mary', 'Kelly', 'Bob', 'Aimy']

print('namelist:', namelist)

 

sort() and sorted() reverse() Example

# Change from [1, 3, 5, 4, 2] to [5, 4, 3, 2, 1]
list = [1, 3, 5, 4, 2]

#1. sort()
list.sort(reverse=True)                 
print('list:', list)

#2. sort(), reverse()
list.sort()                             
list.reverse()                          
print('list:', list)

#3. sorted()
list2 = sorted(list, reverse=True)     
print('list2:', list2)

#4. sorted(), reverse()
list3 = sorted(list)                   
list3.reverse()                         
print('list3:', list3)

list with dictionary

people = [
    {'name': 'noah', 'age': 19},
    {'name': 'liam', 'age': 23},
    {'name': 'jacob', 'age': 9},
    {'name': 'mason', 'age': 21}
]

# 1
people.sort(key=lambda x: x['age'])
print(people)

# 2
result = sorted(people, key=lambda x: x['age'])
print(result)

'Python' 카테고리의 다른 글

Python) Database connection with Oracle  (0) 2022.11.18
Python) try: except:  (0) 2022.11.14
Python) Control statements  (0) 2022.11.06
Python) Dictionary  (0) 2022.11.04
Python) Tuple / Set  (0) 2022.11.03

+ Recent posts