# Learning powerful Python one-liners

#### One-liners shorten the amount of code that must be written and make it cleaner, but they can be challenging for beginners to grasp.


### 1. One-liner loop
Let's begin by creating a list of integers from 0 to 10 using a loop

**Normal Program**
```
num_list=[]
for num in range(0, 11):
   num_list.append(num)
print(num_list)
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
**One-liner Program**
```
num_list=[for num in range(0, 10+1)]
## '10+1' as the upper limit is excluded.
print(num_list)
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

### 2. For loop with 'if' statement
With the help of a for-loop and an if statement inside of a list , we are here producing a list that only includes even integers.

**Normal Program**
```
even_num_list =[]
for num in range(10, 20):
   if num % 2 == 0:
      even_num_list.append(num)
print(even_num_list)
>>> [10, 12, 14, 16, 18]
```
**One-liner Program**
```
even_num_list=[num for num in range(10, 20) if num % 2 == 0]
print(even_num_list)
>>> [10, 12, 14, 16, 18]
```

### 3. if-else statements
Problem statement:
If the age of a boy/girl is less than 18 then he/she is Minor then we need to print: "You are a Minor" or else they are an Adult and we need to print: "You are an Adult"
**Normal Program**
```
age = 12
if age > 18:
   print("You are an Adult")
else:
   print("You are a Minor")
>>> You are a Minor
```
**One-liner Program**
```
result= "You are an Adult" if age > 18 else "You are a Minor"
print(result)
>>> You are a Minor
```
### 4. for loop with if-else statement
Problem statement:
If the number is even, replace it with '*' or else, replace it with '#'.
**Normal Program**
```
num_list=[2,4,8,11,45,23,10]
even_num_count = 0
for num in num_list:
   if num % 2 == 0:
      num_list[num_list.index(num)] = '*'
   else:
      num_list[num_list.index(num)] = '#'
print(num_list)
>>> ['*', '*', '*', '#', '#', '#', '*']
```
**One-liner Program**
```
num_list=[2,4,8,11,45,23,10]
print(['*' if num%2==0 else '#' for num in num_list])
>>> ['*', '*', '*', '#', '#', '#', '*']
```

### 5. Double for loop
Here we are appending multiple tuples inside a list using nested for-loop.
**Normal Program**
```
num_list = []
for num1 in range(1, 3):
     for num2 in range(1, 4):
          num_list.append((num1 ,num2))
print(num_list)
>>> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
```
**One-liner Program**
```
result=[(num1,num2) for num1 in range(1, 3) for num2 in range(1, 4)]
print(result)
>>> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
```
### 6. Multiple assignments
Here we are assigning multiple values to multiple variables.
**Normal Program**
```
a=1
b=2.5
c=6
print("a: {}, b: {}, c: {}".format(a,b,c))
>>> a: 1, b: 2.5, c: 6
```
**One-liner Program**
```
a,b,c = 1, 2.5, 6
print("a: {}, b: {}, c: {}".format(a,b,c))
>>> a: 1, b: 2.5, c: 6
```
Here we are assigning multiple values to multiple variables.
```
a, b, *c =[1,2,3,4,5,6,7]
print("a: {}, b: {}, c: {}".format(a,b,c))
>>> a: 1, b: 2, c: [3, 4, 5, 6, 7]
```
### 7. Swapping two numbers
```
a, b = 5, 9
a, b = b, a
```
### 8. Reading Files
Here we are just reading a text file.
```
lst = [line.strip() for line in open('data.txt')]
print(lst)
```
### 9. Lambda Function
What exactly is a lambda function?
a. Small anonymous functions are called lambda functions.
b. A lambda function can have one expression but any number of arguments.
Here we are calculating the square of a number.
```
num_sqr=lambda x: x**2
num_sqr(10)
>>> 100
```
Here we are multiplying two numbers using the lambda function
```
multiple_two_nums = lambda x,y: x * y
multiple_two_nums(10,20)
>>> 200
```
Here we are filtering odd numbers from a list using the filter function
```
nums = [34, 23, 56, 89, 44, 92]
odds = list(filter(lambda x: x % 2 != 0, nums))
print(odds)
>>> [23, 89]
```
**filter(): **
The filter() function takes two arguments:

1. function -  a function
2. iterable -  (sets, lists, tuples, etc.)
The function returns an iterator where the items are filtered through a function to test if the item is accepted or not.

```
def filter_odd_number(number):
    if number % 2==1:
        return True
    else: 
        return False 
for num in filter(filter_odd_number, [7,5,6,7,8]):print(num)
>>>
7
5
7
```
### 10. TypeCasting Whole List
```
string_list = ['1','2','3','4','5','6']
int_list = list(map(int, string_list))
>>> [1, 2, 3, 4, 5, 6]
```
-------------------------------or--------------------------------
```
int_list = [int(i) for i in string_list]
>>> [1, 2, 3, 4, 5, 6]
float_list = list(map(float, int_list))
>>> [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
```
-------------------------------or---------------------------------
```
float_list = [float(i) for i in int_list]
>>> [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
```
**map() function**

the function takes two parameters:
1. function - a function that performs some action to each element of an iterable
2. iterable - a collection of variables/items such as sets, lists, tuples, etc

Here we are just typecasting from one to another using the map function

**Reference:**
https://wiki.python.org/moin/Powerful%20Python%20One-Liners
https://www.python.org/

*Thank you for reading. If you find something wrong or better ways to do it, let me know in the comments below.*

*If you like the post, hit the 👏 button below so that others may find it useful. You can follow me on [GitHub](https://github.com/rishavnathpati) and connect with me on [Linkedin](https://www.linkedin.com/in/rishav-n-67223bb9/).*
