10 Interesting Python Cool Tricks

Python Methods and Functions

In Python, we can return multiple values ​​—

  1. This is a very unique Python feature that returns multiple values ​​at once.

    def GFG ():

    g = 1  

    f = 2

    return g, f 

     

    x, y = GFG ()

    print (x, y)

    Output:

     (1, 2) 
  2. Allows negative indexing: Python allows negative indexing for its sequences. Index -1 refers to the last element, -2 is the second to last element, etc.

    my_list = [ 'geeks' , ' practice' , 'contribute' ]

    print (my_list [ - 1 ])

    Output:

     contribute 
  3. Concatenate multiple rows. We can easily combine all the tokens available in the list.

    my_list = [ 'geeks' , ' for' , 'geeks' ]

    print ('' .join (my_list))

    Logout :

     pythonengineering 
  4. Sharing is as easy as nothing.

    Take a look. how could we swap two objects in Python.

    x = 1

    y = 2

     

    print ( 'Before Swapping' )

    print (x, y)

     

    x, y = y, x

    print ( 'After Swapping' )

    print (x, y)

    Exit:

     Before Swapping (1, 2) After Swapping (2, 1) 
  5. Do you want to create a file server in Python
    We can easily do this simply by using the below code line.

    python - m SimpleHTTPServer # default port 8080

    You can access your file server from a connected device on the same network.

  6. Want to know the version of Python you are using (just by writing a little code). Use below lines of code —

    import sys

    print ( "My Python version Number: {}" . format (sys.version)) 

    Exit:

     My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36: 49) [GCC 5.4.0 20160609] 

    It prints the version you are using.

  7. Store all the List values ​​in new separate variables.

    a = [ 1 , 2 , 3 ]

    x, y, z =

    print (x)

    print (y)

    print (z) 

    Exit:

     1 2 3 
  8. Convert a nested list into one list simply by using Itertools one line of code. Example — [[1, 2], [3, 4], [5, 6]] should be converted to [1, 2, 3, 4, 5, 6]

    import itertools 

    a = [[ 1 , 2 ], [ 3 , 4 ], [ 5 , 6 ]]

    print ( list (itertools.chain.from_iterable (a)))

    Exit:

     [1, 2, 3, 4, 5, 6] 
  9. I want to transpose the Matrix. Just use zip for that.

    matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]

    print ( zip ( * matrix))

    Exit:

     [(1, 4), (2 , 5), (3, 6)] 
  10. Want to declare some small function, but not using the usual way of declaring. Use a lambda. The lambda keyword in python provides a shortcut to declare an anonymous function.

    subtract = lambda x, y: x - y

    subtract ( 5 , 4 )





Get Solution for free from DataCamp guru