Data Structures Mod 2.1

Cards (34)

  • Python lists are created by placing all the items (elements) inside square brackets [ ], separated by commas.
  • An empty list in Python is represented as myList = [], while an empty list with initial size is represented as myListSize = [].
  • A list of integers in Python is represented as myListInt = [2, 5, 8], while a list of strings is represented as myListName = [“mark”, “jen”, “may”], and a list of mixed data types is represented as myListMix = [7, “Hello”, 2.8].
  • To display the contents of a list in Python, use the print() function.
  • In Python, negative index is used to access elements in a list.
  • To access a range of items in a list, you need to slice a list.
  • The simple slicing operator : in Python allows you to specify where to start the slicing, where to end and specify the step.
  • 3 fruits.insert(2, "berry")
  • 2 points = points.index("c")
  • 12 points = [2, 3, 4, 5, 6, 7, 3, 4, 3, 1, 3]
  • 3 fruits = ['apple', 'cherry', 'durian']
  • 4 names = ["bryan", "romel", carl, mark"]
  • 3 fruits = ["apple", "banana", "berry", "cherry", "durian"]
  • 3 fruits.pop(1)
  • 4 insect = ["ant", "bee", "fly", "spider"]
  • 4 insect = ['ant', 'bee', 'fly']
  • 4 points = ["a", "b", "c", "d", "e", "f", "g"]
  • 4 insect.pop()
  • 4 names.pop(2)
  • 4 names = ['bryan', 'romel', 'mark']
  • 3 fruits = ["apple", "banana", "cherry", "durian"]
  • Slicing a list can be done using methods such as myList[1:6], myList[0:4], myList[1:8:2], myList[0:9:3], myList[8:4:-1], myList[9:1:-2], myList[-6:-2], myList[7:3], myList[-2:-5], myList[-2:-5:-1], myList[:6], myList[3:], myList[:7:2], myList[4::2], myList[:], myList[::], myList[::3], myList[::-1], myList[::-2], myList[4::-1].
  • The index() method returns the index of the first element with the specified value.
  • The copy() method returns a copy of the list.
  • The count() method returns the number of elements with the specified value.
  • The append() method adds an element at the end of the list.
  • The insert() method adds an element at the specified position.
  • The pop() method removes the element at the specified position.
  • The clear() method removes all the elements from the list.
  • The remove() method removes the first item with the specified value.
  • List methods include append(), clear(), copy(), count(), extend(), index(), insert(), pop(), remove(), reverse(), sort(), and sort().
  • The reverse() method reverses the order of the list.
  • The extend() method adds the elements of a list (or any iterable), to the end of the current list.
  • The sort() method sorts the list.