Структура данных списка – это коллекция гетерогенных элементов данных (таких как цифры или символы или даже другие структуры данных), которые каким-то образом структурируются, например, нумерация (индексирование) элементов. Самая базовая структура данных в Python называется списком.
- Список является одной из структур данных последовательности.
- Список – это набор элементов (строки, целые числа или даже другие списки).
- Списки прилагаются в [].
- Каждый элемент в списке имеет назначенное значение индекса.
- Каждый элемент в списке разделен запятой.
- Списки изменяются, что означает, что они могут быть изменены.
emptyList = [] lst = ['one', 'two', 'three', 'four'] # list of strings lst2 = [1, 2, 3, 4] #list of integers lst3 = [[1, 2], [3, 4]] # list of lists lst4 = [1, 'ramu', 24, 1.24] # list of different datatypes
lst = ['one', 'two', 'three', 'four'] #find length of a list print(len(lst)) # this will return 4
lst = ['one', 'two', 'three', 'four'] lst.append('five') # append will add the item at the end print(lst) # print ['one', 'two', 'three', 'four', 'five']
# Syntax: lst.insert(x, y) lst = ['one', 'two', 'four'] lst.insert(2, "three") # will add element y at location x print(last) # print ['one', 'two', 'three', 'four']
Добавить против вставки
Добавьте только добавить элемент в конце списка, но вставьте добавить элемент в любое положение в списке.
# Syntax: lst.remove(x) lst = ['one', 'two', 'three', 'four', 'two'] lst.remove('two') #it will remove the first occurrence of 'two' in a given list print(last) # print ['one', 'three', 'four', 'two']
lst = ['one', 'two', 'three', 'four'] lst2 = ['five', 'six'] lst.append(lst2) # append print(lst) # print ['one', 'two', 'three', 'four', ['five', 'six']] #extend will join the list with list1 # Syntax: lst.extend(lst2) lst.extend(lst2) # extend print(lst) # print ['one', 'two', 'three', 'four', 'five', 'six']
#del to remove item based on index position lst = ['one', 'two', 'three', 'four', 'five'] del lst[1] # remove 'two' from the list print(lst) # print ['one', 'three', 'four', 'five'] #or we can use pop() method a = lst.pop(1) # this will remove 'three' because 'two' is already deleted print(lst) # print ['one', 'four', 'five']
в
#keyword 'in' is used to test if an item is in a list. lst = ['one', 'two', 'three', 'four'] if 'two' in lst: print('AI') # print 'AI' because 'two' is present in the list. #keyword 'not' can combined with 'in' if 'six' not in lst: print('ML') # print 'ML' because 'six' is not present in the list.
#reverse will be reversed the entire list lst = ['one', 'two', 'three', 'four'] lst.reverse() print(lst) # print ['four', 'three', 'two', 'one']
- Самый простой способ сортировки списка – это функция сортированного (списка).
- Это принимает список и возвращает новый список с этими элементами в отсортированном порядке.
- Оригинальный список не изменен.
- Сортированный () необязательный аргумент, например Сортировано (список,), делает его отсортированным назад.
#create a list with numbers numbers = [3, 1, 6, 2, 8] sorted_lst = sorted(numbers) print("Sorted list :", sorted_lst) # print [1, 2, 3, 6, 8] # (original list remained unchanged) #print a list in reverse sorted order print("Reverse sorted list :", sorted(numbers, reverse=True)) # print [8, 6, 3, 2, 1] #sort the list and stored in itself numbers.sort() # this will change the original list [1, 2, 3, 6, 8] print(numbers) # print [1, 2, 3, 6, 8]
Список надежно используется в Python, поэтому, пожалуйста, прочитайте, и я добавлю еще несколько вещей списка в следующем посте, как нажатие нарезки и списка, и некоторые больше. До потом пока. Спасибо за чтение
Оригинал: “https://dev.to/chetanjain645/list-in-python-1cf”