Arvel  Parker

Arvel Parker


Input and Output Techniques Used in Competitive Programming in Python

So you started competitive programming, but having difficulty in taking input and formatting output even in the simplest ones? No problem you are at the right place, this post will tell you the most important input and output techniques used in competitive programming in python.

#python3 #input-methods #coding #programming #competitive-programming

What is GEEK

Buddha Community

Input and Output Techniques Used in Competitive Programming in Python
Noah Saunders

Noah Saunders


How List Comprehension Works in Python

List Comprehension in Python

Lists are a helpful and frequently used feature in Python.

And list comprehension gives you a way to create lists while writing more elegant code that is easy to read.

In this beginner-friendly article, I'll give an overview of how list comprehension works in Python. I'll also show plenty of code examples along the way.

Let's get started!

How to use a for loop to create a list in Python

One way to create a list in Python is by using a for loop.

For example, you can use the range() function to create a list of numbers ranging from 0 - 4.

#first create an empty list
my_list = []

#iterate over the numbers 0 - 4 using the range() function
#range(5) creates an iterable, starting from 0 up to (but not including) 5
#Use the .append() method to add the numbers 0 - 4 to my_list

for num in range(5):
#print my_list

#[0, 1, 2, 3, 4]

What if you already have a list of numbers, but want to create a new list with their squares?

You could again use a for loop, like so:

#initial list of numbers
numbers = [1,2,3,4,5,6]

#create a new,empty list to hold their squares
square_numbers = []

#iterate over initial list
#multiply each number by itself
#use .append() method, to add the square to the new list, square_numbers

for num in numbers: 
    square_numbers.append(num * num)

#print new list

#[1, 4, 9, 16, 25, 36]

But there is a quicker and more succinct way to achieve the same results – by using list comprehension.

What is list comprehension in Python? A syntax overview

When you're analyzing and working with lists in Python, you'll often have to manipulate, modify, or perform calculations on every single item in the list, all at once.

You may also need to create new lists from scratch, or create a new list based on the values of an already existing list.

List comprehension is a fast, short, and elegant way to create lists compared to other iterative methods, like for loops.

The general syntax for list comprehension looks like this:

new_list = [expression for variable in iterable]

Let's break it down:

  • List comprehensions start and end with opening and closing square brackets, [].
  • Then comes the expression or operation you'd like to perform and carry out on each value inside the current iterable. The results of these calculations enter the new list.
  • The expression is followed by a for clause.
  • variable is a temporary name you want to use for each item in the current list that is going through the iteration.
  • The in keyword is used to loop over the iterable.
  • iterable can be any Python object, such as a list, tuple, string and so on.
  • From the iteration that was performed and the calculations that took place on each item during the iteration, new values were created which are saved to a variable, in this case new_list. The old list (or other object) will remain unchanged.
  • There can be an optional if statement and additional for clause.

How to use list comprehension in Python

Using the same example from earlier on, here is how you'd create a new list of numbers from 0 - 4 with the range() function in just one single line, using list comprehension:

new_list = [num for num in range(5)]


#[0, 1, 2, 3, 4]

This has the same output as the for loop example, but with significantly less code!

Let's break it down:

  • the iterable in this case is a sequence of numbers from 0 to 4, using range(5). range() constructs a list of numbers.
  • You use the in keyword to iterate over the numbers.
  • The num following the for clause is a variable, a temporary name for each value in the iterable. So num would be equal to 0 in the first iteration, then num would be equal to 1 in the next iteration and so on, until it reached and equalled the number 4, where the iteration would stop.
  • The num before the for clause is an expression for each item in the sequence.
  • Finally, the new list (or other iterable) that is created gets stored in the variable new_list.

You can even perform mathematical operations on the items contained in the iterable and the result will be added to the new list:

new_list = [num * 2 for num in range(5)]


#[0, 2, 4, 6, 8]

Here each number in range(5) will be multiplied by two and the new value will be stored in the variable new_list.

What if you had a pre-existing list where you wanted to manipulate and modify each item in it? This would be similar to the example from earlier on, where we created a list of squares.

Again, you can achieve that with just one line of code, using list comprehension:

#initial list
numbers = [1,2,3,4,5,6]

#new list
#num * num is the operation that takes place to create the squares

square_numbers = [num * num for num in numbers]


[1, 4, 9, 16, 25, 36]

How to use conditionals with list comprehension in Python

Optionally, you can use an if statement with a list comprehension.

The general syntax looks like this:

new_list = [expression for variable in iterable if condition == True]

Conditionals act as a filter and add an extra check for additional precision and customisation when creating a new list.

This means that the value in the expression has to meet certain criteria and a certain condition you speficy, in order to go in the new list.

new_list = [num for num in range(50) if num % 2 == 0]


#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

In the example above, only the values where the condition num % 2 == 0 is checked and evaluates to True will enter new_list.

The modulo operator is used on every single one of the numbers in the sequence of numbers starting from 0 and ending in 49.

If the remainder of the numbers when divided by 2 is 0, then and only then does it enter the list.

So in this case, it creates a list of only even numbers.

You can then make it as specific as you want.

For example, you could add more than one condition, like so:

new_list = [num for num in range(50) if  num > 20 and num % 2 == 0]


#[22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

In this example, there are two conditions num > 20 and num % 2 == 0.

The and operator indicates that both have to be met in order for the value to be added to the new list.

The values that don't meet the conditions are excluded and are not added.

How to use list comprehension on strings in Python

You can create a new list with the individual characters contained in a given string.

fave_language_chars = [letter for letter in "Python"]


#['P', 'y', 't', 'h', 'o', 'n']

The new list that gets created is comprised of all the separate letters contained in the string "Python", which acts as an iterable.

Just like numbers, you can perform operations on the characters contained in a string and customize them depending on how you want them to be in the new list you create.

If you wanted all letters to be uppercase, you would do the following:

fave_language_chars_upper = [letter.upper() for letter in "Python"]


#['P', 'Y', 'T', 'H', 'O', 'N']

Here you use the .upper() method to convert every single letter in "Python" to uppercase and add them to the fave_language_chars_upper variable.

The same goes if you wanted all your letters to be lowercase - you'd instead use the lower() method.


And there you have it! You now know the basics of list comprehension in Python.

It offers an elegant and concise syntax for creating new lists based on existing lists or other iterables.

Original article source at


Ray  Patel

Ray Patel


top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Python range() Function Explained with Examples

In Python, can use use the range() function to get a sequence of indices to loop through an iterable. You'll often use range() in conjunction with a for loop.

In this tutorial, you'll learn about the different ways in which you can use the range() function – with explicit start and stop indices, custom step size, and negative step size.

Let's get started.

Understanding Python's range() Function

Before looking at the different ways of using the range() function, you've got to understand how it works.

The range() function returns a range object.  
This range object in turn returns the successive items in the sequence when you iterate over it.

As stated above, the range function does not return a list of indices. Rather, it returns a range object which returns the indices as and when you need them. This makes it memory-efficient as well.  

You can use the range() function with the following general syntax:


When you use this syntax in conjunction with a loop, you can get a sequence of indices from start up to but not including stop , in steps of step.

  • You must specify the required argument stop, which can be any positive integer. If you specify a floating point number instead, you'll run into a TypeError as shown:
my_range = range(2.5)

  • If you don't specify the start index, the default start index of 0 is used.
  • If you don't specify the step value, the default step size of 1 is used.

In the subsequent sections, you'll learn about the different ways of using the range() function.

How to Use Python's range() Function to Loop Through Any Iterable

As mentioned in the previous section, you only need one positive integer to use the range() function. The syntax is shown below:


You can use the above line of code to get a sequence from 0 through stop-1 : 0, 1, 2, 3,..., stop-1.  

▶ Consider the following example where you call range() with 5 as the argument. And you loop through the returned range object using a for loop to get the indices 0,1,2,3,4 as expected.

for index in range(5):

If you remember, all iterables in Python follow zero-indexing. This is why it's convenient to use range() to loop through iterables.

An iterable of length len has 0, 1, 2, ..., len-1 as the valid indices. So to traverse any iterable, all you need to do is to set the stop value to be equal to len. The sequence you'll get – 0, 1, 2, ..., len-1 – is the sequence of valid indices.

▶ Let's take a more helpful example. You have a list my_list. You can access all items in the list by knowing their indices, and you can get those indices using range() as shown below:

my_list = ["Python","C","C++","JavaScript","Julia","Rust","Go"]
for index in range(len(my_list)):
  print(f"At index {index}, we have {my_list[index]}")

Remember, you can use Python's built-in function len to get the length of any iterable. In the above code, you use both the valid indices, and the list items at those valid indices. Here's the output:

Notice how my_list is 7 items long, and the indices obtained are from 0 through 6, as expected.

Sometimes, you may need to use negative integers instead. In this case, if you use only the stop argument, you'll not get the desired output, though the code doesn't throw an error.

This is because the default start value is assumed to be 0, and you cannot count up from 0 to -5.

for index in range(-5):
  print (index)

How to Use Python's range() Function with Explicit Start and End Indices

You may not always want to start at zero. You can start at any arbitrary index by setting the start value to the index that you'd like to start from. The syntax is as follows:


In this case, you'll be able to get the sequence: start, start + 1, start + 2, and so on up to stop-1.

▶ In the example below, you're starting at 10, count all the way up to but not including 15 in steps of 1.

for index in range(10,15):


In the previous section, you saw how using only the stop argument won't work when you need negative integers. However, when you specify start and stop indices explicitly, you can as well work with negative integers.

▶ In this example, you're trying to count up from -5 in steps of 1. Always keep in  mind that the counting stops at the value that's one less than the stop index.

for index in range(-5,0):

How to Use Python's range() Function with a Custom Step Size

Instead of traversing an iterable sequentially, you may sometimes want to stride through it, accessing every k-th element. This is when the optional step argument comes in handy. The general syntax is shown below:


When you use this syntax and loop through the range object, you can go from start to stop-1 with strides of size step.

  • You'll get the sequence: start, start + step, start + 2*step, and so on up to start + k*step such that  start + k*step < stop and start + (k+1)*step > stop.

▶ In the example below, you'd like to go from 0 to 20 in steps of 2. Notice how the last index printed out is 19. This is because, if you take another step, you'll be at 21 which is greater than 20.

Always remember, the last value you get can be as close to stop as possible, but can never be stop.

for index in range(1,20,2):


How to Use Python's range() Function with a Negative Step Size

So far, you've learned to use the range() function with start and stop indices, and a specific step size, all the while counting up from start to stop.

If you need to count down from an integer, you can specify a negative value for step. The general syntax is:

  • The range object can now be used to return a sequence that counts down from start in steps of negative_step, up to but not including stop.
  • The sequence returned is start, start - negative_step, start - 2*negative_step, and so on up to start - k*negative_step such that start - k*negative_step > stop and start - (k+1)*negative_step < stop.
  • There's no default value for negative step – you must set negative_step = -1 to count down covering each number.

▶ In this example, you'd like to count down from 20 in steps of -2. So the sequence is 20, 18, 16, all the way down to 2. If you go another 2 steps lower, you'll hit 0, which you cannot as its smaller than the stop value of 1.

for index in range(20,1,-2):

It's easy to see that start > stop to be able to count down.

for index in range(10,20,-1):
 #Nothing is printed - the sequence is empty.

▶ In the above example, you try counting down from 10 to 20 which is impossible. And you don't get any output which is expected.

How to Use Python's range() and reversed() Functions to Reverse a Sequence

If you need to access the elements of an iterable in the reverse order, you can use the range() function coupled with the reversed() function.

Python's built-in reversed() function returns a reverse iterator over the values of a given sequence.

▶ Let's take our very first example, where we used range(5). In the example below, we call reversed() on the range object. And we see that we've counted down from 4 to 0.

for index in reversed(range(5)):
  print (index)

As you can see, this is equivalent to using range(4,-1,-1). If you prefer, you may use the reversed() function instead of negative_step argument discussed in the previous section.


In this tutorial, you've learned the different ways in which you can use the range() function. You can try a few examples to get a different sequence each time. This practice will help you use range() effectively when looping through iterables.

Original article source at


f-strings in Python - Explained with Code Examples

When you're formatting strings in Python, you're probably used to using the format() method.

But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super helpful in string formatting.

In this tutorial, you'll learn about f-strings in Python, and a few different ways you can use them to format strings.

What are f-Strings in Python?

Strings in Python are usually enclosed within double quotes ("" ) or single quotes (''). To create f-strings, you only need to add an f  or an F before the opening quotes of your string.

For example, "This" is a string whereas f"This" is an f-String.

How to Print Variables using Python f-Strings

When using f-Strings to display variables, you only need to specify the names of the variables inside a set of curly braces {}. And at runtime, all variable names will be replaced with their respective values.

If you have multiple variables in the string, you need to enclose each of the variable names inside a set of curly braces.

The syntax is shown below:

f"This is an f-string {var_name} and {var_name}."

▶ Here's an example.

You have two variables, language and school, enclosed in curly braces inside the f-String.

language = "Python"
school = "freeCodeCamp"
print(f"I'm learning {language} from {school}.")

Let's take a look at the output:

I'm learning Python from freeCodeCamp.

Notice how the variables language and school have been replaced with Python and freeCodeCamp, respectively.

How to Evaluate Expressions with Python f-Strings

As f-Strings are evaluated at runtime, you might as well evaluate valid Python expressions on the fly.

▶ In the example below, num1 and num2 are two variables. To calculate their product, you may insert the expression num1 * num2 inside a set of curly braces.

num1 = 83
num2 = 9
print(f"The product of {num1} and {num2} is {num1 * num2}.")

Notice how num1 * num2 is replaced by the product of num1 and num2 in the output.

The product of 83 and 9 is 747.

I hope you're now able to see the pattern.

In any f-String, {var_name}, {expression} serve as placeholders for variables and expressions, and are replaced with the corresponding values at runtime.

Head over to the next section to learn more about f-Strings.

How to Use Conditionals in Python f-Strings

Let's start by reviewing Python's if..else statements. The general syntax is shown below:

if condition:
  # do this if condition is True <true_block>
  # do this if condition is False <false_block>

Here, condition is the expression whose truth value is checked.

  • If the condition evaluates to True, the statements in the if block (<true_block>) are executed.
  • If the condition evaluates to False, the statements in the else block (<false_block>) are executed.

There's a more succinct one-line equivalent to the above if..else blocks. The syntax is given below:

<true_block> if <condition> else <false_block>

In the above syntax,<true block> is what's done when the condition is True, and <false_block> is the statement to be executed when the condition is False.

This syntax may seem a bit different if  you haven't seen it before. If it makes things any simpler, you may read it as, "Do this if condition is True; else, do this".

This is often called the ternary operator in Python as it takes 3 operands in some sense – the true block, the condition under test, and the false block.

▶ Let's take a simple example using the ternary operator.

Given a number num, you'd like to check if it's even. You know that a number is even if it's evenly divisible by 2. Let's use this to write our expression, as shown below:

num = 87;
print(f"Is num even? {True if num%2==0 else False}")

In the above code snippet,

  • num%2==0 is the condition.
  • If the condition is True, you just return True indicating that num is indeed even, and False otherwise.
Is num even? False

In the above example, num is 87, which is odd. Hence the conditional statement in the f-String is replaced with False.

How to Call Methods with Python f-Strings

So far, you've only seen how to print values of variables, evaluate expressions, and use conditionals inside f-Strings. And it's time to level up.

▶ Let's take the following example:

author = "jane smith"
print(f"This is a book by {author}.")

The above code prints out This is a book by jane smith.

Wouldn't it be better if it prints out This is a book by Jane Smith. instead? Yes, and in Python, string methods return modified strings with the requisite changes.

The title() method in Python returns a new string that's formatted in the title case - the way names are usually formatted (First_name Last_name).

To print out the author's name formatted in title case, you can do the following:

  • use the title() method on the string author,
  • store the returned string in another variable, and
  • print it using an f-String, as shown below:
author = "jane smith"
a_name = author.title()
print(f"This is a book by {a_name}.")

This is a book by Jane Smith.

However, you can do this in just one step with f-Strings. You only need to call the title() method on the string author inside the curly braces within the f-String.

author = "jane smith"
print(f"This is a book by {author.title()}.")

When the f-String is parsed at runtime,

  • the title() method is called on the string author, and
  • the returned string that's formatted in title case is printed out.

You can verify that in the output shown below.

This is a book by Jane Smith.

You can place method calls on any valid Python object inside the curly braces, and they'll work just fine.

How to Call Functions Inside Python f-Strings

In addition to calling methods on Python objects, you can also call functions inside f-Strings. And it works very similarly to what you've seen before.

Just the way variable names are replaced by values, and expressions are replaced with the result of evaluation, function calls are replaced with the return value from the function.

▶ Let's take the function choice() shown below:

def choice(c):
  if c%2 ==0:
    return "Learn Python!"
    return "Learn JavaScript!"

The above function returns "Learn Python!" if it's called with an even number as the argument. And it returns "Learn JavaScript!" when the argument in the function call is an odd number.

▶ In the example shown below, you have an f-String that has a call to the choice function inside the curly braces.

print(f"Hello Python, tell me what I should learn. {choice(3)}")

As the argument was an odd number (3), Python suggests that you learn JavaScript, as indicated below:

Hello Python, tell me what I should learn. Learn JavaScript!

If you call the function choice() with an even number, you see that Python tells you to learn Python instead. 🙂

print(f"Hello Python, tell me what I should learn. {choice(10)}")
Hello Python, tell me what I should learn. Learn Python!

And that ends our tutorial on a happy note!


In this tutorial, you've learned how you can use f-Strings to:

  • print values of variables,
  • evaluate expressions,
  • call methods on other Python objects, and
  • make calls to Python functions.

Original article at

Related Posts

Explains string formatting using the format() method.


Python Tips and Tricks for Competitive Programming

Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips:

  • **Converting a number into a List of digits using map() Function: **

Below is the implementation to convert a given number into a list of digits:

#competitive programming #python programs #python-itertools #python-library #python-list #python-list-of-lists #python-map