Python Lists
Lists
List is a collection of ordered items separated by comma and enclosed within square brackets.
Lists are indexed and allow duplicate items.
EntityList = ["Body", "Face", "Edge"]
print(EntityList[0])
Output
Body
Unlike strings, lists are mutable i.e. possible to change their contents.
EntityList[0] = "Model"
Use len() method to find the number of items in the list.
Add Items
append()add to end of the list.
EntityList = ["Body", "Face"]
EntityList.append ("Edge")
print (EntityList)
Output
['Body', 'Face', 'Edge']
insert()add at a specified position.
EntityList = ["Body", "Face"]
EntityList.insert (0, "Model")
print (EntityList)
Output
['Model', 'Body', 'Face']
Remove Items
remove()removes the specified item.
EntityList = ["Body", "Face", "Edge"]
EntityList.remove ("Face")
print (EntityList)
Output
['Body', 'Edge']
pop()removes the item with the specified position.
EntityList = ["Body", "Face", "Edge"]
EntityList.pop (1)
print (EntityList)
Output
['Body', 'Edge']
Delete List or Items
EntityList = ["Body", "Face", "Edge"]
del EntityList[1]print (EntityList)
del EntityList
Output['Body', 'Edge']
Accessing index 1 in this list in future will throw an error, which is not in the case when you remove the item by pop(). When you remove an item by pop() only the item is removed and the memory is not deleted.
Clear List
empties the list.
EntityList = ["Body", "Face", "Edge"]
EntityList.clear()
print (EntityList)
Output
[]
Copy List
Copies the items in the list to another list.
copy()EntityList = ["Body", "Face", "Edge"]
EntityList1 = EntityList.copy()
print (EntityList1)
Output
['Body', 'Face', 'Edge']
list()EntityList = ["Body", "Face", "Edge"]
EntityList1 = list(EntityList)
print (EntityList1)
Output
['Body', 'Face', 'Edge']
List Traversal
EntityList = ["Body", "Face", "Edge"] for e in EntityList: print(e)
Output
Body
Face
Edge
Check List for an item
EntityList = ["Body", "Face", "Edge"] if"Face"in EntityList: print("Face")
Output
Face
Nested List
Create list containing other lists.
EntityCAD = ["Body", "Face", "Edge"]
EntityFEM = ["Node", "Element"]
EntityList = (EntityCAD, EntityFEM)
print (EntityList)
Output(['Body', 'Face', 'Edge'], ['Node', 'Element'])