List - Python

  • varL= [value1, value2] => Initialize list
  • varL[N] => Accessing element of (N-1) position
    • varL[N] = value => Changing value of element of (N-1) position
    • varL[-N] => Accessing element of (len(varL)-N-1) position
  • len(varL) => Returns length of list
  • Slicing
    • varL[N1:N2:N3] => Access elements from N1 to (N2-1) jumping N3 indexes
    • varL[:] => Returns all elements by assuming varL[0:len(varL)]
  • del varL => Delete the list
  • varL.append(value) => Adds value at the end of the list
    • varL3 = varL1 + varL2
  • `varL1.extend(varL2) => Appends list2 at the end of list1
  • varL.sort() => Sorts the list in ascending order
    • varL.sort(reverse = True) => Sorts the list in descending order
  • varL.reverse() => Reverses the list
  • varL.index() => Returns index of first occurrence of element
  • varL.count(value) => Returns the count value of given element
  • varL2 = varL1.copy() => Make true copy of the list
    • varL2 = varL1 => Both will point to the same reference
  • varL.insert(index, value) => Insert value at given index
  • varL.pop() => Delete & Return the element, Last element by default
  • varL.remove(value) => Removes the first occurrence of that value
  • varL.clear => Clears the whole list
  • max(varL)
  • min(varL)
  • Checks if element is present in the list
        if value in varL:
            # statements
        else:
            # statements
    
  • Loop Elements
        for element in varL:
            print(element)
    
  • Enumerate Function
        for index, element in enumerate(varL):
            print(index, element)
    
  • List Comprehension
    • Creating new list from from other iterables like lists, tuples, dictionaries, sets, strings, arrays
    • [Expression(item) for element in iterable
    • [Expression(item) for element in iterable if condition
  • Map Function => Apply the given function to every element in the list, Takes a sequesnce and returns a new sequence, Higher-order function
        varName = map(functionName, varL)
        print(list(varName)) # Convert to list
    
  • Filter Function => Considers only the elements that satisfy the condition given
        # Returns true/false
        def functionName(a) {
            return a>N;
        }
        varName = filter(functionName, varL)
        print(list(varName)) # Convert to list
    
  • Reduce Function => Apply the function to the first two element then the result with the nest element and so on
        from functools import reduce
        varName = filter(functionName, varL)
    
Share: