Learning how to construct python list


a=[4,5,2,3,4,8,6,9,2,5,4,2]

  1. To add values in the existing list a.
  2. a.append(2)
    print(a)

    In [213]: [4, 5, 2, 3, 4, 8, 6, 9, 2, 5, 4, 2, 2]

  3. To insert value in the list in position 1
  4. a.insert(1,8)
    print(a)

    In [216]: [4, 8, 5, 2, 3, 4, 8, 6, 9, 2, 5, 4, 2, 2]

  5. To remove values from the list, following command will remove 1 from the list.
  6. a.remove(2)
    print(a)

    [4, 8, 5, 3, 4, 8, 6, 9, 2, 5, 4, 2, 2]

  7. To remove value with position: ( Important: position always starts at 0,1,2….. , hence the value 4 is at position 0
  8. a.remove(a[2])
    print(a)

    [4, 8, 3, 4, 8, 6, 9, 2, 5, 4, 2, 2]

  9. To access last element of the list.
  10. a.remove(a[-1])
    print(a)

    [4, 8, 3, 4, 8, 6, 9, 5, 4, 2, 2]

  11. To count the number of times an element is present in the list.
  12. a.count(a[4])
    Out[226]: 3
  13. To sort the values in list
  14. a.sort()
    print(a)

    [2, 2, 3, 4, 4, 4, 5, 6, 8, 8, 9]

    ******To construct multidimensional list******

  15. To construct multidimensional list
  16. a=[[2,2],[3,2],[4,3],[8,7]]
  17. How to access elements of multi-dimensional list
  18. a[1]

    [3, 2]

  19. To access element within elements, here third list is [8,7]
  20. a[3][0]

    8