Не каждый язык имеет красивую структуру данных, такую ​​как список Python!

вступление

Список — одна из очень популярных структур данных, используемых в Python. Мы используем списки для многих вещей, от итерации до хранения значений. Сегодняшней темой будет Список Python, волнуйтесь!

В python индекс элемента списка также начинается с 0, что означает, что первый элемент имеет индекс 0, второй элемент имеет индекс 1 и так далее.

Список Python не ограничивает тип списка, а это означает, что в списке могут быть разные типы данных.

Распространенные способы инициации списка:

# initiate an empty list
a = []
# b is now [1, 2, 3, 4]
b = [1, 2, 3, 4]
# c is now ['h', 'e', 'l', 'l', 'o']
c = list('hello')
# d is now [0, 1, 2, 3, 4]
d = range(5)

Общие функции списка:

# initiate list with one element
# a now is [1]
a = [1]
# lst.append(ele) append elements to the end of the list
# a now is [1, 2]
a.append(2)
# lst.pop(k) will remove element at the Kth index
# a now is [2]
a.pop(0)
# lst.insert(k, ele) inserts element at the Kth index
# a now is [3, 2]
a.insert(0, 3)

Общие операции со списками:

a = ['a', 'd', 'e', 'b']
# lst[k] returns the element at Kth position (position starts from
#   0).
# this evaluates to be 'd' since the element 'd' is at position 1
a[1]
# lst1 + lst2 produces a new list that has elements of both lst1 and
#   lst2.
# c is now [1, 2]
c = [1] + [2]
# lst*k produce a new list that has k times elements of lst
# c is now [1, 2, 1, 2, 1, 2]
c = c*3
# lst[k:d] slice the list starting from position K to position D
#   (again, the end index of the slicing is exclusive, meaning that #   it does not include the Dth element in this example)
# Note that the start_index is default to be 0, and the end_index is
#   default to be the last position of that list.
c = [0, 1, 2, 3, 4]
# d is now [0, 1]
d = c[0:2]
# d is now [0, 1, 2, 3, 4]
d = c[:]
# d is now [1, 2, 3, 4] 
d = c[1:]
# d is now [0]
d = c[:1]
# list[::-1] produce a new list with reverse elements order from
#   list.
# e is now [5, 4, 3, 2, 1]
e = [1, 2, 3, 4, 5][::-1]

Резюме

Хорошо, это сегодняшний 3-минутный питон!

Сегодня мы узнали о некоторых способах инициации списка, некоторых общих функциях списка и некоторых общих операциях со списками. Надеюсь, этот пост поможет!

Дайте мне знать, как я могу улучшить, я буду писать больше подобных сообщений в будущем!