lists (1D and 2D) Flashcards
what is the name of a list called
identifier
what do lists look like
shoppingList = [“apple” , “banana”, “orange” , “mango”]
- always use square brackets
how to print specific item in the list
eg. print(shoppingList[2]) will print the third index
how to check the length of a list
print(len(shoppingList))
- it will print number of indexes
how to add items to a list
eg. shoppingList.append(“berries”)
- normal brackets
- method is .append
- always adds to end of the list
so now shoppingList = [“apple”, “banana” , “orange” , “mango” , “berries”]
how to remove items from a list
eg. shoppingList.remove(shoppingList[0])
- removes first item on list
-method is .remove
OR shoppingList.remove(“apple”)
so now shoppingList = [“banana” , “orange” , “mango” , “berries”]
how to check if an item is part of a list
containsbanana = “banana” in shoppingList
print(containsbanana)
if value printed is true then banana is in the list
how to check which index an item is in the list
print(shoppingList.index(“orange”))
- will print the number item orange is in the list
- method is .index
how to concatenate lists
eg. abc = [“1”, “2”, “3”] xyz = [“4”, “5”, “6”]
abc + xyz will print [“1”, “2”, “3”, “4”, “5”, “6”]
or abc += xyz makes abc = [“1”, “2”, “3”, “4”, “5”, “6”]
how to add something to a list at a specific index
eg. want to add pineapple to be the third item in list
shoppingList.insert(2, “pineapple”)
- method is .insert
so now shoppingList = [“apple”, “banana”, “pineapple”, “orange”, “mango”, “berries”]
what are 2D lists
- lists within lists
eg. abc = [[“1”, “2”, “3”], [“4”, “5”, “6”]] - index[0] consists of first list [“1”, “2”, “3”]
- index[1] consists of second list [“4”, “5”, “6”]
how to get a specific a value in a 2D list
eg. abc = [[“1”, “2”, “3”], [“4”, “5”, “6”]]
- we want to find 6, which is in the second list so index[1]
- and it is the third item in that list so index[3]
print(abc[1][2]) gives 6