Skip to content

Instantly share code, notes, and snippets.

@ndthanh

ndthanh/07_lists.py

Created May 9, 2020
Embed
What would you like to do?
# Python List
fruits = ["tao", "chuoi", "cam", "mit", "dua hau", "kiwi", "ca chua"]
# print(type(fruits))
# Access item in list, access first item by index, start from 0
# print(fruits[0])
# print(fruits[1])
# print(fruits[2])
# print(fruits[len(fruits)-1])
# Access item in list negative indexing style, first item reverse, first item from right
# fruits[-1]
# fruits[-2]
# Access item in list range style [2:5], [:5], [2:], [-4: -1]
# [2:5] index >=2 AND index < 5, inclue 2, exclude 5, [2,5)
# fruits[2:5]
# fruits[:5]
# fruits[2:]
# fruits[-4:-1]
# Change value of a item in list
# fruits[0] = "Tao"
# loop through a list
# for fruit in fruits:
# print(fruit)
# check if item in list
"chuoi" in fruits
"chuoi " in fruits
# List length
len(fruits)
# Add items to end
fruits.append("sau rieng")
# Insert item vs add item
fruits.insert(0, "dua chuot")
# Remove item - with remove()
fruits.remove("dua chuot")
# Remove item - with pop()
fruits.pop()
fruits.pop(1)
# Remove item - with del
del fruits[0]
del fruits
# Empty a list - clear()
fruits.clear()
# Copy a list? Why
list2 = fruits.copy()
# Join 2 lists
hoa_qua = ["Cherry", "dau tay"]
danh_sach = fruits + hoa_qua
# Reverse order of a list
fruits.reverse()
# Sort a list
fruits.sort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment