A Cheatsheet for Python Lists
# *** Creating a list ***
list1 = []
list2 = [1, "item1", 2.2]
list3 = [list1, list2, "a text", 1234]
print(list3[1][1])
# Output: item1
print(list3[-1]) # negative index are counted from the end.
# Output: 1234
#
# *** Length of a list ***
len3 = len(list3)
print(len3)
# Output: 4
#
# *** Appending new list items ***
for i in range(10, 14):
list3.append(i)
list3.append([t for t in range(0, 10, 3)])
print(list3)
# Output: [[], [1, 'item1', 2.2], 'a text', 1234, 10, 11, 12, 13, [0, 3, 6, 9]]
print(list3[-1]) # negative index are counted from the end.
# Output: [0, 3, 6, 9]
#
# Inserting new items into a list.
print(list2)
# Output: [1, 'item1', 2.2]
list2.insert(2, 222)
print(list2)
# Output: [1, 'item1', 222, 2.2]
#
# Extending a list.
list2.extend([t for t in range(0, 10, 3)])
print(list2)
# Output: [1, 'item1', 222, 2.2, 0, 3, 6, 9]
#
# Removing an items from a list.
list2.remove("item1")
print(list2)
# Output: [1, 222, 2.2, 0, 3, 6, 9]
#
# Using pop method to get and remove an item.
val1 = list2.pop()
print(val1)
# Output: 9
val2 = list2.pop(2) # index.
print(val2)
# Output: 2.2
#
# Slicing a list.
list4 = ["A", "B", "C", "D", "E", "F", "G"]
print(list4[:2])
# Output: ['A', 'B']
print(list4[:-2])
# Output: ['A', 'B', 'C', 'D', 'E']
print(list4[2:])
# Output: ['C', 'D', 'E', 'F', 'G']
print(list4[2:4])
# Output: ['C', 'D']
print(list4[::-1])
# Output: [['G', 'F', 'E', 'D', 'C', 'B', 'A']
No comments:
Post a Comment