- List
cars = ['Honda', 'KIA', 'BMW', 'Lada']
print(cars)
print(cars[0])
print(cars[1])
print(cars[-1])
print(cars[-2])
['Honda', 'KIA', 'BMW', 'Lada']
Honda
KIA
Lada
BMW
[ ] squares brackets must be used to create a list
Notice how index starts from 0, not 1
- Modifying elements in List
- Here, I have replaced 'Honda' with 'Toyota' in the list
cars = ['Honda', 'KIA', 'BMW', 'Lada']
print(cars)
cars[0] = 'Toyota'
print(cars)
['Honda', 'KIA', 'BMW', 'Lada']
['Toyota', 'KIA', 'BMW', 'Lada']
- Appending elements in List
- Here, I'm going to add 'Citroen' to the list
cars = ['Honda', 'KIA', 'BMW', 'Lada']
print(cars)
cars.append('Citroen')
print(cars)
['Honda', 'KIA', 'BMW', 'Lada']
['Honda', 'KIA', 'BMW', 'Lada', 'Citroen']
Notice how .append() put the element to the last end of the list
- Inserting elements in List
- Here, I'm going to add 'Ferrari' to the list as the first index [0]
cars = ['Honda', 'KIA', 'BMW', 'Lada']
print(cars)
cars.insert(0, 'Ferrari')
print(cars)
['Honda', 'KIA', 'BMW', 'Lada']
['Ferrari', 'Honda', 'KIA', 'BMW', 'Lada']
Notice how the rest of the elements shifted to the right
- Removing elements in List
- Here, I'm going to remove 'Ferrari' in the list
cars = ['Ferrari','Honda', 'KIA', 'BMW', 'Lada']
print(cars)
del cars[0]
print(cars)
['Ferrari', 'Honda', 'KIA', 'BMW', 'Lada']
['Honda', 'KIA', 'BMW', 'Lada']
- Removing elements in List (and re-using them after removed)
- Here, I'm going to remove 'Ferrari' and 'Lada' from the list and re-use them
cars = ['Ferrari','Honda', 'KIA', 'BMW', 'Lada']
print(cars)
popped_car_0 = cars.pop(0)
popped_car_4 = cars.pop()
popped_cars = [popped_car_0, popped_car_4]
print(cars)
print(popped_cars)
['Ferrari', 'Honda', 'KIA', 'BMW', 'Lada']
['Honda', 'KIA', 'BMW']
['Ferrari', 'Lada']
Notice if you don't specify the index with .pop() method, the last element is removed from the list
there's also .remove() method if you want to remove element in the list and re-use them
It is used when you don't know the position of the element in the list unlike the example above
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
- Sorting a List
- .sort() method sorts the list in alphabetical order, permanently
- .sort(reverse=True) method sorts the list in reverse-alphabetical order, permanently
- sorted() function sorts the list in alphabetical order, temporarily
- .reverse() method reverses the order of the list, permanently, disregarding the alphabetical order
'Python > Python Crash Course' 카테고리의 다른 글
Python Crash Course: 챕터 6 (0) | 2024.06.28 |
---|---|
Python Crash Course: 챕터 5 (0) | 2024.06.27 |
Python Crash Course: 챕터 4 (0) | 2024.06.26 |
Python Crash Course: 챕터 2 (0) | 2024.06.23 |
Python Crash Course: 챕터 1 (0) | 2024.06.19 |