Python tricks

  1. List comprehension

     squares = [x**2 for x in range(10)]
  2. Dict Comprehension

     result = {x: x**2 for x in range(10)}
  3. REMOVING DUPLICATES FROM THE LIST

      fruits = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
      new = list(set(fruits))
      ['banana', 'apple', 'pear', 'orange'] 
  4. unpack from list

     fruit, num, date = ['apple', 5,(2021, 11, 7)]
  5. list slice, sequence[start:stop:step]

      x = [10, 5, 13, 4, 12, 43, 7, 8]
      result = x[1:6:2]
      result [5, 4, 43]
  6. Compare two Unordered list

    from collections import Counter
    one = [33, 22, 11, 44, 55]
    two = [22, 11, 44, 55, 33]
    Counter(one) == Counter(two)
    sorted(one) == sorted(two)
  7. Reverse String and List

    print('Anand Tripathi'[::-1])
    # ihtapirT dnanA
    print([1,2,3][::-1])
    # [3, 2, 1]
  8. Inputting Secret Information
    taking a username and password as input from the user

     from getpass import getpass
     uname = input('Enter Username: ')
     pwd = getpass('Enter password: ')
     print('Logging In....')
  9. Opening a website

     import webbrowser
     webbrowser.open("https://medium.com/pythonistas")
  10. The Walrus(:=) Operator
    Normal Way :

      xs = [1,2,3]
      n=len(xs)
      if n>2:
         print(n)

    Using walrus operators:

     xs = [1,2,3]
     if (n:=len(xs)>2):
         print(n)

    Declare and assign the value at the same time

  11. Difference between two lists
    use the set’s symmetric_difference operation of the set of differences.

     list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
     list2 = ['Scott', 'Eric', 'Kelly']set1 = set(list1)
     set2 = set(list2)list3 = list(set1.symmetric_difference(set2))
     # {'Smith', 'Emma'}
     # Or
     set1-set2
     # {'Smith', 'Emma'}
  12. Merge two dictionaries or two lists

     # two dicts
     name = dict(first_name='Tom', last_name='Anderson')
     details = dict(age=28, sex='Male')
     person = {**name, **details}
    
     # two list
     list1 = ['Scott', 'Eric', 'Kelly']
     list2= list1 = ['Emma', 'Smith']
     whole_lst= [*list1, *list2]
  13. For-else operation

     # For example assume that I need to search through a list and process each item until a flag   item is found and 
     # then stop processing. If the flag item is missing then an exception needs to be raised.
    for i in mylist:
       if i == theflag:
          break
       process(i)
    else:
        raise ValueError("List argument missing terminal flag.")
  14. Converting lists into a dictionary

     user = [“Peter”, “John”, “Sam”]
     age = [23,19,34]
     dictionary = dict(zip(user, age))
     print(dictionary)