List
from:
-----------------1-------------------------------------
- Create a list
As opposed to int
, bool
etc., a list is a compound data type; you can group values together:
a = "is"b = "nice"my_list = ["my", "list", a, b]
--------------2----------------------------------------
-
Create list with different types
A list can contain any Python type. Although it's not really common, a list can also contain a mix of Python types including strings, floats, booleans, etc.
# area variables (in square meters)
hall = 11.25kit = 18.0liv = 20.0bed = 10.75bath = 9.50# Adapt list areas
areas = ["hallway",hall, "kitchen",kit, "living room", liv, "bedroom",bed, "bathroom", bath]# Print areas
print(areas)
---------------3-------------------------------------
- Select the valid list
my_list = [el1, el2, el3]
both of them are correct:A. [1, 3, 4, 2]
B. [[1, 2, 3], [4, 5, 7]]
C. [1 + 2, "a" * 5, 3]
Subsetting lists
-
Subset and conquer
x = ["a", "b", "c", "d"]x[1]x[-3] # same result!
-
Subset and calculate
x = ["a", "b", "c", "d"]print(x[1] + x[3])
-
Slicing and dicing
x = ["a", "b", "c", "d"]x[1:3]
The elements with index 1 and 2 are included, while the element with index 3 is not.
-
Slicing and dicing (2)
x = ["a", "b", "c", "d"]x[:2]x[2:]x[:]
-
Subsetting lists of lists
x = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]x[2][0]x[2][:2]
List Manipulation
--------------------1-----------------------
Replace list elements
x = ["a", "b", "c", "d"]x[1] = "r"x[2:] = ["s", "t"] -------------------2------------
Extend a list
x = ["a", "b", "c", "d"]y = x + ["e", "f"] -------------------3------------
Delete list elements
x = ["a", "b", "c", "d"]del(x[1]) Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change! The ; sign is used to place commands on the same line. The following two code chunks are equivalent:
# Same linecommand1; command2# Separate linescommand1command2 So if delete two items, pay more attention here. better to use like this del(areas[-4:-2]), instead of "del(areas[10]); del(areas[11])","del(areas[10:11])" "del(areas[-3]); del(areas[-4])", ----------------------------------------------4--------------------------------------------------------------
Inner workings of lists
if use "areas_copy = areas", then they are the same thing, when value in one of them changed, both of them will be changed.
if use "areas_copy = areas[:]", then they are not the same thing, when value in one of them changed, the other one will Not be changed.