Top 10 Python One-Liners

Source: levelup.gitconnected.com

Python is a very simple and easy-to-use language that provides a fascinating experience with its simplicity, popularity, and its famous one-liners to the users.

So, Let’s have a look at some of its one-liners. This would help you so much during a Python interview. Also, while we’re at it, do test yourself with Python Interview Questions to be better prepared for it: Visit here!

1. How to Swap Two Variables?

Let’s start with a simple program that is used for swapping two variables with each other. This is one of the easiest methods that anyone with little effort can write. The need to use a temp variable or apply any sort of arithmetic operations is eliminated.

Source: maketecheasier.com

Python code to swap two variables

  1. # declaring the two variables
  2. x = 50
  3. y = 100
  4. #printing the initial values of the variables
  5. print(“The initial value for x variable:”, x)
  6. print(“The initial value for y variable:”, y)
  7. # writing the code for swapping the two variables
  8. x , y = y , x
  9. # printing the swapped variables
  10. print(“The interchanged value for x variable:”, x)
  11. print(“The interchanged value for y variable:”, y)

Output:

The initial value for x variable: 50

The initial value for y variable: 100

The interchanged value for x variable: 100

The interchanged value for y variable: 50

Python One liner code to swap two variables

  1. # declaring the two variables
  2. x , y = 50 , 100
  3. #printing the initial values of the variables
  4. print(“The initial value for x variable:”, x)
  5. print(“The initial value for y variable:”, y)
  6. # writing the code for swapping the two variables
  7. x , y = y , x
  8. # printing the swapped variables
  9. print(“The interchanged value for x variable:”, x)
  10. print(“The interchanged value for y variable:”, y)

Output:

The initial value for x variable: 50

The initial value for the y variable: 100

The interchanged value for x variable: 100

The interchanged value for the y variable: 50

2. How to Assign Multiple Variables?

When defining many variables, it is very time-consuming to define each and every variable separately. Users can declare multiple variables using single lines of codes by using commas to assign multiple values to variables. Following are the examples for multiple variable assignments.

Source: pimylifeup.com

Python code to assign multiple variables

  1. # declaring the multiple variables
  2. x = 50
  3. y = 100
  4. z = ‘Hello, this is an example of assigning multiple variables.’
  5. # printing the assigned variables
  6. print(“The value of x variable is:”, x)
  7. print(“The value of y variable is:”, y)
  8. print(“The value of z variable is:”, z)

Output:

The value of the x variable is: 50

The value of the y variable is: 100

The value of the z variable is: Hello, this is an example of assigning multiple variables.

Python One liner code to assign multiple variables

  1. # declaring the multiple variables
  2. x, y, z = 50, 100, ‘Hello, this is an example of assigning multiple variables.’
  3. # printing the assigned variables
  4. print(“The value of x variable is:”, x)
  5. print(“The value of y variable is:”, y)
  6. print(“The value of z variable is:”, z)

Output:

The value of the x variable is: 50

The value of the y variable is: 100

The value of the z variable is: Hello, this is an example of assigning multiple variables.

3. How to Find Sum of Even and Odd Numbers In a List?

Find the sum of even or odd numbers in a list can be solved using many different approaches, following are the best and the easiest way to solve such problems.

Source: youtube.com

Python code to find the sum of even numbers in a list

  1. # creating a list containing both even and odd numbers
  2. list = [10,15,20,25,30]
  3. # declaring summation
  4. summation = 0
  5. # writing the code for the sum of even number of the list
  6. for i in range(5):
  7. if list[i]%2 == 0:
  8.  summation = summation + list[i]
  9. # printing the sum of even number of the list
  10. print(“The addition of even number of the list is:”, summation)

Output:

The addition of an even number to the list is: 60

Python One liner code to find the sum of even numbers in a list

  1. # creating a list containing both even and odd numbers
  2. list = [10,15,20,25,30]
  3. # writing the code for the sum of even number of the list
  4. summation = sum([num for num in list if num%2 == 0])
  5. # printing the sum of even number of the list
  6. print(“The addition of even number of the list is:”, summation)

Output:

The addition of an even number to the list is: 60

Python code to find the sum of odd numbers in a list

  1. # creating a list containing both even and odd numbers
  2. list = [10,15,20,25,30]
  3. # declaring summation
  4. summation = 0
  5. # writing the code for the sum of the odd number of the list
  6. for i in range(5):
  7. if list[i]%2 != 0:
  8. summation = summation + list[i]
  9. # printing the sum of odd number of the list
  10. print(“The addition of odd number of the list is:”, summation)

Output:

The addition of an odd number to the list is: 40

Python One liner code to find the sum of even numbers in a list

  1. # creating a list containing both even and odd numbers
  2. list = [10,15,20,25,30]
  3. # writing the code for the sum of the odd number of the list
  4. summation = sum([num for num in list if num%2 == 0])
  5. # printing the sum of odd numbers of the list
  6. print(“The addition of an odd number of the list is:”, summation)

Output:

The addition of an odd number to the list is: 40

4. How to Eliminate Items (multiple) from a List?

If the user wants to delete or remove single or multiple elements or items from a particular list, the del keyword can be used to serve the purpose.

Source: codegrepper.com

Python One liner code to delete multiple elements from a list

  1. # creating a list containing both even and odd numbers
  2. list = [56 , 85 , 97 , 65 , 23 , 12]
  3. # declaring the items to be removed from the list
  4. items_to_be_removed = {12 , 97}
  5. list = [item for item in list if item not in items_to_be_removed]
  6. # printing the updated list
  7. print(“The updated list from which the desired elements are eliminated is: “, list)

Output:

The updated list from which the desired elements are eliminated is:  [56, 85, 65, 23]

Python One liner code to delete multiple even elements from a list

  1. # creating a list containing both even and odd numbers
  2. list = [56 , 85 , 97 , 65 , 23 , 12]
  3. # declaring the items to be removed from the list
  4. list = [ item for item in list if item % 2 == 0]
  5. # printing the updated list
  6. print (“The updated list from which the desired elements are eliminated is: “, list)

Output:

The updated list from which the desired elements are eliminated is:  [56, 12]

Python One liner code to delete multiple odd elements from a list

  1. # creating a list containing both even and odd numbers
  2. list = [56 , 85 , 97 , 65 , 23 , 12]
  3. # declaring the items to be removed from the list
  4. list = [ item for item in list if item % 2 != 0]
  5. # printing the updated list
  6. print(“The updated list from which the desired elements are eliminated is: “, list)

Output:

The updated list from which the desired elements are eliminated is:  [85, 97, 65, 23]

Python One liner code for deleting multiple elements from a list

# creating a list containing both even and odd numbers

list = [56 , 85 , 97 , 65 , 23 , 12]

# writing the code for deleting the unwanted items from the list

# m:n signifies the items between the index m and index n will be deleted

del list[2:5]

# printing the updated list

print(“The updated list from which the desired elements are eliminated is: “, list)

Output:

The updated list from which the desired elements are eliminated is:  [56, 85, 12]

Python One liner code for deleting multiple elements from a list

# creating a list containing both even and odd numbers

list = [56 , 85 , 97 , 65 , 23 , 12]

# writing the code for deleting the unwanted items from the list

# m::n signifies the items from the index m will start getting removed from the list following the skip counting of n

del list[1::2]

# printing the updated list

print(“The updated list from which the desired elements are eliminated is: “, list)

Output:

The updated list from which the desired elements are eliminated is:  [56, 97, 23]

5. How to Read Files?

In this Python program, list comprehension is used. In the first step, open a text file, and use a “for loop” function to read it line by line. In the end, remove all unnecessary space with the help of the “strip” function.

Source: linuxhint.com

Python One liner code to read files

  1. list_example = [text.strip() for text in open(‘draft.txt’)]
  2. print(list_example)
  3. list(open(‘draft.txt’))
  4. ##Using “with” code will also close the file after use
  5. with open(“draft.txt”) as f: list_example=[text.strip() for text in f]
  6. print(list_example)

6. How to Write Data to File?

By using the code mentioned in the below program, first, a file draft.txt will be created if not existing, and then “This is an example for writing data to a file.” will be written in the file.

Python One liner code to write data to files

  1. with open(“draft.txt”,’a’,newline=’\n’) as f: f.write(“This is an example for writing data to a file.”)

Methods and their description:

Method for creating a new file:
  1. ‘x’ mode: If the user wants to create a new file, then this method can be implemented to serve the purpose. If the file already exists the executed operation fails.
Defaults Methods
  1. ‘r’ mode: This mode is used to open the file for reading, it is one of the default modes.
  2. ‘t’ mode: This mode is used to open the file in text mode, it is one of the default modes.
Other methods
  1. ‘w’ mode: This mode is used to open the file for writing. If the file is absent,  then it automatically creates a new file, and if the file already exists, then the method makes the changes in the existing file.
  2. ‘x’ mode: If the user wants to create a new file, then this method can be implemented to serve the purpose. If the file already exists the executed operation fails.
  3. ‘a’ mode: This method is used to open the file in append mode. It automatically creates a new file if the file is absent.
  4. ‘b’ mode: This mode is used to open the file in binary mode.
  5. ‘+’ mode: if the user wants to open the file in both reading and writing (or updating the file) mode, this method can be implemented to serve the purpose.

7. How to Create Lists?

Python lists are considered one of the most versatile data types that allow users to work with multiple elements at once.

Source: linuxhint.com

Python One liner code to create lists

  1. # creating a new list
  2. list = [i for i in range(0,30)]
  3. # printing the new created list
  4. print(“The new created list is:\n”, list)

Output:

The new created list is:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Python One liner code to create lists

  1. # creating a new list
  2. list = list(range(0,30))
  3. # printing the new created list
  4. print(“The new created list is:\n”, list)

Output:

The new created list is:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Python One liner code to create list of strings

  1. # creating a list of string
  2. list = [(“The names of the days are: “+i) for i in [‘Monday’, ‘Tuesday’,’Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Sunday’]]
  3. # printing the new created list of string
  4. print(“The new created list of string is:\n”, list)

Output:

The newly created list of strings is:

[‘The names of the days are: Monday’, ‘The names of the days are: Tuesday’, ‘The names of the days are: Wednesday’, ‘The names of the days are: Thursday’, ‘The names of the days are: Friday’, ‘The names of the days are: Saturday’, ‘The names of the days are: Sunday’]

8. How to Check the Presence of a Number in a List?

There are many situations when it is required to check the presence of a number in a given list. Users can use the following oneliner code example to easily check if the respective number is present in the list.

Source: pythonguides.com

Python One liner code to check the availability of a number in the list

  1. # declaring the number to be checked for in the list
  2. num = 10
  3. # creating the list
  4. list = [i for i in range (0,30)]
  5. # printing the list
  6. print(“The list is: \n “, list)
  7. # writing the code to check the presence of the declared number in the list
  8. if num in list:
  9. # printing the result
  10. print(‘Yes, the number is present in the list.’)

Output:

The list is:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Yes, the number is present in the list.

9. How To Find the Max Value?

The method can be used to find the maximum value.

Source: pythonguides.com

Python One liner code to find the maximum value

  1. # creating the list
  2. list = [i for i in range (0,30)]
  3. # printing the list
  4. print(“The list is: \n “, list)
  5. # writing the code  to find the maximum value, and then printing the maximum value
  6. print(max(list, key=lambda value: int(value)) )

Output:

The list is:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

29

10. How to Replace a Text with Some Other Text?

It is very simple to replace the text with some other text. The following approach can be used.

Source: codegrepper.com

Python One liner code to replace a text with some other text

  1. String = “Python is a very simple language to learn. With proper dedication, it can be mastered in a couple of months.”.replace(“Python”, ‘C’)
  2. print(String)

Output:

C is a very simple language to learn. With proper dedication, it can be mastered in a couple of months.

Conclusion

We have shared all the useful and important information about how one-liners can be so effective and useful. It is a fantastic way of coding. Also, did you know that there is a newer version of Python?