Lists
# an empty list
>>> L = []
# a list with an integer, a float, and a string
>>> L = [2, -3.56, "XyZ"]
# a list with an integer and a list
>>> L = [4, ["abc", 8.98]]# the list
>>> L = [4, ["abc", 8.98]]
# get the first item of L
>>> L[0]
4
# get the second element of L
>>> L[1]
["abc", 8.98]
# get the first item of L's second item
>>> L[1][0]
"abc"# the list
>>> L = ["Leonard", "Penny", "Sheldon"]
# change the second item of L via indexing
>>> L[1] = "Raj"
>>> print(L)
["Leonard", "Raj", "Sheldon"]
# change multiple items of L via slicing
>>> L[0:2] = ["Amy", "Howard"]
>>> print(L)
["Amy", "Howard", "Sheldon"]
# delete the first item of L via indexing and using the 'del' statement
>>> del L[0]
>>> print(L)
["Howard", "Sheldon"]
# delete multiple items of L via slicing and using the 'del' statement
>>> del L[0:2]
>>> print(L)
[]| Method | Synopsis |
|---|---|
L.append(X) |
Append an item to an existing list |
L.insert(i, X) |
Append an item to an existing list in position i |
L.extend([X0, X1, X2]) |
Extend an existing list with the items from another list |
L.index(X) |
Get the index of the first instance of the argument in an existing list |
L.count(X) |
Get the cardinality of an item in an existing list |
L.sort() |
Sort the items in an existing list |
L.reverse() |
Reverse the order of the items in an existing list |
L.copy() |
Get a copy of an existing list |
L.pop(i) |
Remove the item at the given position in the list, and return it |
L.remove(X) |
Remove the first instance of an item in an existing list |
L.clear() |
Remove all items in an existing list |
# create two lists
>>> L1 = ["Leonard", "Penny", "Sheldon"]
>>> L2 = ["Howard", "Raj", "Amy", "Bernadette"]
# expand an existing list with .append()
>>> L2.append("Priya")
>>> print(L2)
["Howard", "Raj", "Amy", "Bernadette", "Priya"]
# concatenate L1 and L2 with .extend()
>>> L1.extend(L2)
>>> print(L1)
["Leonard", "Penny", "Sheldon", "Howard", "Raj", "Amy", "Bernadette", "Priya"]# create a list
>>> L = ["Howard", "Raj", "Amy", "Bernadette", "Priya"]
# reverse the list's item positions
>>> L.reverse()
>>> print(L)
["Priya", "Bernadette", "Amy", "Raj", "Howard"]
# sort the list's items
>>> L.sort()
>>> print(L)
["Amy", "Bernadette", "Howard", "Priya", "Raj"]