Found 10784 Articles for Python

What are the best practices for using if statements in Python?

karthikeya Boyini
Updated on 30-Jul-2019 22:30:22

532 Views

Here are some of the steps that you can follow to optimize a nested if...elif...else.1. Ensure that the path that'll be taken most is near the top. This ensures that not multiple conditions are needed to be checked on the most executed path.2. Similarly, sort the paths by most use and put the conditions accordingly.3. Use short-circuiting to your advantage. If you have a statement like:if heavyOperation() and lightOperation():Then consider changing it toif lightOperation() and heavyOperation():This will ensure that heavyOperation is not even executed if lightOperation is false. Same can be done with or conditions as well.4. Try flattening the ... Read More

What are the best practices for using loops in Python?

Samual Sam
Updated on 05-Mar-2020 10:05:05

584 Views

This is a language agnostic question. Loops are there in almost every language and the same principles apply everywhere. You need to realize that compilers do most heavy lifting when it comes to loop optimization, but you as a programmer also need to keep your loops optimized.It is important to realize that everything you put in a loop gets executed for every loop iteration. The key to optimizing loops is to minimize what they do. Even operations that appear to be very fast will take a long time if the repeated many times. Executing an operation that takes 1 microsecond ... Read More

Python: Can not understand why I am getting the error: Can not concatenate 'int' and 'str' object

Ayush Gupta
Updated on 12-Mar-2020 12:31:58

79 Views

This error is coming because the interpreter is replacing the %d with i and then trying to add 1 to a str, ie, adding a str and an int. In order to correct this, just surround the i+1 in parentheses. exampleprint("\ Num %d" % (i+1))

Python: Cannot understand why the error - cannot concatenate 'str' and 'int' object ?

Jayashree
Updated on 13-Mar-2020 05:15:39

111 Views

This can be corrected by putting n+1 in brackets i.e. (n+1)for num in range(5):     print ("%d" % (num+1))Using %d casts the object following % to string. Since a string object can't be concatnated with a number (1 in this case) interpreter displays typeerror.

How to make loops run faster using Python?

Samual Sam
Updated on 05-Mar-2020 09:55:17

827 Views

This is a language agnostic question. Loops are there in almost every language and the same principles apply everywhere. You need to realize that compilers do most heavy lifting when it comes to loop optimization, but you as a programmer also need to keep your loops optimized.It is important to realize that everything you put in a loop gets executed for every loop iteration. They key to optimizing loops is to minimize what they do. Even operations that appear to be very fast will take a long time if the repeated many times. Executing an operation that takes 1 microsecond ... Read More

How to create a lambda inside a Python loop?

Lakshmi Srinivas
Updated on 05-Mar-2020 09:54:01

1K+ Views

You can create a list of lambdas in a python loop using the following syntax −Syntaxdef square(x): return lambda : x*x listOfLambdas = [square(i) for i in [1,2,3,4,5]] for f in listOfLambdas: print f()OutputThis will give the output −1 4 9 16 25You can also achieve this using a functional programming construct called currying. examplelistOfLambdas = [lambda i=i: i*i for i in range(1, 6)] for f in listOfLambdas:    print f()OutputThis will give the output −1 4 9 16 25

How do I loop through a JSON file with multiple keys/sub-keys in Python?

Sravani S
Updated on 05-Mar-2020 08:14:19

13K+ Views

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −{    "id": "file",    "value": "File",    "popup": {       "menuitem": [          {"value": "New", "onclick": "CreateNewDoc()"},          {"value": "Open", "onclick": "OpenDoc()"},          {"value": "Close", "onclick": "CloseDoc()"}       ]    } }ExampleYou can load it in your python program and loop ... Read More

How can I loop over entries in JSON using Python?

karthikeya Boyini
Updated on 05-Mar-2020 08:11:45

1K+ Views

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −{    "id": "file",    "value": "File",    "popup": {       "menuitem": [       {"value": "New", "onclick": "CreateNewDoc()"},       {"value": "Open", "onclick": "OpenDoc()"},       {"value": "Close", "onclick": "CloseDoc()"}       ]    } }ExampleYou can load it in your python program and loop over its keys ... Read More

How to execute Python multi-line statements in the one-line at command-line?

Samual Sam
Updated on 05-Mar-2020 08:08:02

2K+ Views

There are multiple ways in which you can use multiline statements in the command line in python. For example, bash supports multiline statements, which you can use like −Example$ python -c ' > a = True > if a: > print("a is true") > 'OutputThis will give the output −a is trueIf you prefer to have the python statement in a single line, you can use the newline between the commands. example$ python -c $'a = Trueif a: print("a is true");'OutputThis will give the output −a is true

How to loop through multiple lists using Python?

V Jyothi
Updated on 05-Mar-2020 08:06:15

516 Views

The most straightforward way seems to use an external iterator to keep track. Note that this answer considers that you're looping on same sized lists. examplea = [10, 12, 14, 16, 18] b = [10, 8, 6, 4, 2] for i in range(len(a)):    print(a[i] + b[i])OutputThis will give the output −20 20 20 20 20ExampleYou can also use the zip method that stops when the shorter of a or b stops.a = [10, 12, 14, 16, 18] b = [10, 8, 6] for (A, B) in zip(a, b):    print(A + B)OutputThis will give the output −20 20 20

Advertisements