How to reverse a string in Python?
How to append element in the list
How to compare two lists in Python
How to convert int to string in Python
How to convert list to dictionary in Python
How to reverse a number in Python
How to reverse a string in Python?
Python String is the collection of the Unicode character. Python has numerous functions for string manipulation, but Python string library doesn't support the in-built "reverse()" function. But there are various ways to reverse the string. We are defining the following method to reverse the Python String.
Using for loop
Using while loop
Using the slice operator
Using the reversed() function
Using the recursion
Using for loop
Here, we will reverse the given string using for loop.
def reverse_string(str):
str1 = "" # Declaring empty string to store the reversed string
for i in str:
str1 = i + str1
return str1 # It will return the reverse string to the caller function
str = "JavaTpoint" # Given String
print("The original string is: ",str)
print("The reverse string is",reverse_string(str))
Function call
Output:
('The original string is: ', 'JavaTpoint')
('The reverse string is', 'tniopTavaJ')
Explanation-
In the above code, we have declared the reverse_string() function and passed the str argument. In the function body, we have declared empty string variable str1 that will hold the reversed string.
Next, the for loop iterated every element of the given string, join each character in the beginning and store in the str1 variable.
After the complete iteration, it returned the reverse order string str1 to the caller function. It printed the result to the screen.
Using while loop
We can also reverse a string using a while loop. Let's understand the following example.
Example -
# Reverse string
# Using a while loop
str = "JavaTpoint" # string variable
print ("The original string is : ",str)
reverse_String = "" # Empty String
count = len(str) # Find length of a string and save in count variable
while count > 0:
reverse_String += str[ count - 1 ] # save the value of str[count-1] in reverseString
count = count - 1 # decrement index
print ("The reversed string using a while loop is : ",reverse_String)# reversed string
Output:
('The original string is : ', 'JavaTpoint')
('The reversed string using a while loop is : ', 'tniopTavaJ')
Explanation:
In the above code, we have declared a str variable that holds string value. We initialized a while loop with a value of the string.
In each iteration, the value of str[count - 1] concatenated to the reverse_String and decremented the count value. A while completed its iteration and returned the reverse order string.
Using the slice ([]) operator
We can also reverse the given string using the extended slice operator. Let's understand the following example.
Example -
# Reverse a string
# using slice syntax
# reverse(str) Function to reverse a string
def reverse(str):
str = str[::-1]
return str
s = "JavaTpoint"
print ("The original string is : ",s)
print ("The reversed string using extended slice operator is : ",reverse(s))
Output:
('The original string is : ', 'JavaTpoint')
('The reversed string(using extended slice syntax) is : ', 'tniopTavaJ')
Explanation:
Generally, a slice operator accepts three parameters - start, stop and step. We provided the no value to start and end index, which indicates the start index is 0 and the end is n-1 by default. The step size is -1; it means the string continues the traverse from the end and goes to the 1 index position.
Using reverse function with join
Python provides the reversed() function to reverse the string. Let's understand the following example.
Example -
#reverse a string using reversed()
# Function to reverse a string
def reverse(str):
string = "".join(reversed(str)) # reversed() function inside the join() function
return string
s = "JavaTpoint"
print ("The original string is : ",s)
print ("The reversed string using reversed() is : ",reverse(s) )
Output:
('The original string is : ', 'JavaTpoint')
('The reversed string using reversed() is : ', 'tniopTavaJ')
Explanation:
In the function body, we declared the empty string separated by .dot operator. The reversed() string returned the reverse string it joined with the empty string separated using the join() function.
Using recursion()
The string can also be reversed using the recursion. Recursion is a process where function calls itself. Consider the following example.
Example -
reverse a string
using recursion
def reverse(str):
if len(str) == 0: # Checking the lenght of string
return str
else:
return reverse(str[1:]) + str[0]
str = "Devansh Sharma"
print ("The original string is : ", str)
print ("The reversed string(using recursion) is : ", reverse(str))
Output:
('The original string is : ', 'JavaTpoint')
('The reversed string(using reversed) is : ', 'tniopTavaJ')
Explanation:
In the above code, we have defined a function that accepts the string as an argument.
How to append element in the list
Python provides built-in methods to append or add elements to the list. We can also append a list into another list. These methods are given below.
append(elmt) - It appends the value at the end of the list.
insert(index, elmt) - It inserts the value at the specified index position.
extends(iterable) - It extends the list by adding the iterable object.
Let's understand these methods by the following example.
append(elmt)
This function is used to add the element at the end of the list. The example is given below.
Example -
names = ["Joseph", "Peter", "Cook", "Tim"]
print('Current names List is:', names)
new_name = input("Please enter a name:\n")
names.append(new_name) # Using the append() function
print('Updated name List is:', names)
Output:
Current names List is: ['Joseph', 'Peter', 'Cook', 'Tim']
Please enter a name:
Devansh
Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']
insert(index, elmt)
The insert() function adds the elements at the given an index position. It is beneficial when we want to insert element at a specific position. The example is given below.
Example -
list1 = [10, 20, 30, 40, 50]
print('Current Numbers List: ', list1)
el = list1.insert(3, 77)
print("The new list is: ",list1)
n = int(input("enter a number to add to list:\n"))
index = int(input('enter the index to add the number:\n'))
list1.insert(index, n)
print('Updated Numbers List:', list1)
Output:
Current Numbers List: [10, 20, 30, 40, 50]
The new list is: [10, 20, 30, 77, 40, 50]
enter a number to add to list:
45
enter the index to add the number:
1
Updated Numbers List: [10, 45, 20, 30, 77, 40, 50]
extend(iterable)
The extends() function is used to add the iterable elements to the list. It accepts iterable object as an argument. Below is the example of adding iterable element.
Example -
list1 = [10,20,30]
list1.extend(["52.10", "43.12" ]) # extending list elements
print(list1)
list1.extend((40, 30)) # extending tuple elements
print(list1)
list1.extend("Apple") # extending string elements
print(list1)
Output:
[10, 20, 30, '52.10', '43.12']
[10, 20, 30, '52.10', '43.12', 40, 30]
[10, 20, 30, '52.10', '43.12', 40, 30, 'A', 'p', 'p', 'l', 'e']
How to compare two lists in Python
Python provides multiple ways to compare the two lists. Comparison is the process when the data items of are checked against another data item of list, whether they are the same or not.
list1 - [11, 12, 13, 14, 15]
list2 - [11, 12, 13, 14, 15]
Output - The lists are equal
The methods of comparing two lists are given below.
The cmp() function
The set() function and == operator
The sort() function and == operator
The collection.counter() function
The reduce() and map() function
The cmp() function
The Python cmp() function compares the two Python objects and returns the integer values -1, 0, 1 according to the comparison
.
Note - It doesn't use in Python 3.x version.
The set() function and == operator
Python set() function manipulate the list into the set without taking care of the order of elements. Besides, we use the equal to operator (==) to compare the data items of the list. Let's understand the following example.
Example -
list1 = [11, 12, 13, 14, 15]
list2 = [12, 13, 11, 15, 14]
a = set(list1)
b = set(list2)
if a == b:
print("The list1 and list2 are equal")
else:
print("The list1 and list2 are not equal")
Output:
The list1 and list2 are equal
Explanation:
In the above example, we have declared the two lists to be compared with each other. We converted those lists into the set and compared each element with the help of == operator. All elements are equal in both lists, then if block executed and printed the result.
The sort() method with == operator
Python sort() function is used to sort the lists. The same list's elements are the same index position it means; lists are equal.
Note - In the sort() method, we can pass the list items in any order because we are sorting the list before comparison.
Let's understand the following example -
Example -
import collections
list1 = [10, 20, 30, 40, 50, 60]
list2 = [10, 20, 30, 50, 40, 70]
list3 = [50, 10, 30, 20, 60, 40]
# Sorting the list
list1.sort()
list2.sort()
list3.sort()
if list1 == list2:
print("The list1 and list2 are the same")
else:
print("The list1 and list3 are not the same")
if list1 == list3:
print("The list1 and list2 are not the same")
else:
print("The list1 and list2 are not the same")
Output:
The list1 and list3 are not the same
The list1 and list2 are not the same
The collection.counter() function
The collection module provides the counter(), which compare the list efficiently. It stores the data in dictionary format : and counts the frequency of the list's items.
Note - The order of the list's elements doesn't matter in this function.
Example -
import collections
list1 = [10, 20, 30, 40, 50, 60]
list2 = [10, 20, 30, 50, 40, 70]
list3 = [50, 10, 30, 20, 60, 40]
if collections.Counter(list1) == collections.Counter(list2):
print("The lists l1 and l2 are the same")
else:
print("The lists l1 and l2 are not the same")
if collections.Counter(list1) == collections.Counter(list3):
print("The lists l1 and l3 are the same")
else:
print("The lists l1 and l3 are not the same")
Output:
The lists list1 and list2 are not the same
The lists list1 and list3 are the same
The reduce() and map()
The map() function accepts a function and Python iterable object (list, tuple, string, etc) as an arguments and returns a map object. The function implements to each element of the list and returns an iterator as a result.
Besides, The reduce() method implements the given function to the iterable object recursively.
Here, we will use both methods in combination. The map() function would implement the function (it can be user-define or lambda function) to every iterable object and the reduce() function take care of that would apply in recursive manner.
Note - We need to import the functool module to use the reduce() function.
Let's understand the following example.
Example -
import functools
list1 = [10, 20, 30, 40, 50]
list2 = [10, 20, 30, 50, 40, 60, 70]
list3 = [10, 20, 30, 40, 50]
if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list2), True):
print("The list1 and list2 are the same")
else:
print("The list1 and list2 are not the same")
if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list3), True):
print("The list1 and list3 are the same")
else:
print("The list1 and list3 are not the same")
Output:
The list1 and list2 are not the same
The list1 and list3 are the same
How to convert int to string in Python
We can convert an integer data type using the Python built-in str() function. This function takes any data type as an argument and converts it into a string. But we can also do it using the "%s" literal and using the .format() function. Below is the syntax of the str() function.
Syntax -
str(integer_Value)
Let's understand the following example.
Example - 1 Using the str() function
n = 25
# check and print type of num variable
print(type(n))
print(n)
# convert the num into string
con_num = str(n)
# check and print type converted_num variable
print(type(con_num))
print(con_num)
Output:
<class 'int'>
25
<class 'str'>
25
Example - 2 Using the "%s" integer
n = 10
# check and print type of n variable
print(type(n))
# convert the num into a string and print
con_n = "% s" % n
print(type(con_n))
Output:
<class 'int'>
<class 'str'>
Example - 3: Using the .format() function
n = 10
# check and print type of num variable
print(type(n))
# convert the num into string and print
con_n = "{}".format(n)
print(type(con_n))
Output:
<class 'int'>
<class 'str'>
Example - 4: Using f-string
n = 10
# check and print type of num variable
print(type(n))
# convert the num into string
conv_n = f'{n}'
# print type of converted_num
print(type(conv_n))
Output:
<class 'int'>
<class 'str'>
How to convert list to dictionary in Python
Lists and Dictionaries are two data structure which is used to store the Data. List stores the heterogeneous data type and Dictionary stores data in key-value pair. Here, we are converting the Python list into dictionary. Since list is ordered and dictionary is unordered so output can differ in order. Python list stores the element in the following way.
student_marks = [56, 78, 96, 37, 85]
On the other hand, Dictionary is unordered, and stores the unique data. It stores the data in key value pair where each key is associated with it value. Python Dictionary stores the data in following way.
student_dict = {'Abhinay': 56, 'Sharma': 78, 'Himanshu': 96, 'Peter': 37}
In this tutorial, we will learn the conversion Python list to dictionary.
Sample Input:
Input : ['Name', 'Abhinay', 'age', 25, 'Marks', 90]
Output : {'Name', 'Abhinay', 'age', 25, 'Marks', 90}
Input : ['a', 10, 'b', 42, 'c', 86]
Output : {'a', 10, 'b', 42, 'c', 86}
Let's understand the following methods.
Method - 1 Using Dictionary Comprehension
We can convert the list into dictionary using the dictionary comprehension. Let's understand the following code.
Example -
student = ["James", "Abhinay", "Peter", "Bicky"]
student_dictionary = { stu : "Passed" for stu in student }
print(student_dictionary)
Output:
{'James': 'Passed', 'Abhinay': 'Passed', 'Peter': 'Passed', 'Bicky': 'Passed'}
Explanation -
In the above code, we have created a student list to be converted into the dictionary. Using the dictionary compression, we converted the list in dictionary in a single line. The list elements tuned into key and passed as a value.
Let's understand another example.
Example - 2
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
square_dict = {n: n*n for n in list1}
print(square_dict)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Explanation:
In the above code, we have created square_dict with number-square key/value pair.
Method - 2 Using zip() function
The zip() function is used to zip the two values together. First, we need to create an iterator and initialize to any variable and then typecast to the dict() function.
Let's understand the following example.
Example -
def Convert_dict(a):
init = iter(list1)
res_dct = dict(zip(init, init))
return res_dct
# Driver code
list1 = ['x', 1, 'y', 2, 'z', 3]
print(Convert_dict(list1))
Output:
{'x': 1, 'y': 2, 'z': 3}
How to reverse a number in Python
Using while loop
Using recursion
Reverse a number using Python while loop
First, we understand the algorithm of this program. It will make easy to understand the program logic. Once you get the logic, you can write the program in any language, not only Python.
Algorithm
Input Integer: number
(1) Initialize variable revs_number = 0
(2) Loop while number > 0
(a) Multiply revs_number by 10 and add remainder of number
divide by 10 to revs_number
revs_number = revs_number*10 + number%10;
(b) Divide num by 10
(3) Return revs_number
Let's implement the above algorithm in program.
Program
# Ask for enter the number from the use
number = int(input("Enter the integer number: "))
# Initiate value to null
revs_number = 0
# reverse the integer number using the while loop
while (number > 0):
# Logic
remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10
# Display the result
print("The reverse number is : {}".format(revs_number))
Output:
Enter the integer number: 12345
The reverse number is: 54321
Explanation -
Let's understand this program step by step.
We initialed a number variable for user input and variable revs_number initial value to null.
First Iteration
Reminder = number %10
Reminder = 12345%10 = 5
Reverse = Reverse *10 + Reminder Initial value of revs_number is null
Reverse = 0 * 10 + 5 = 0 + 5 = 5
Number = Number //10
Number = 1234 //10 = 1234 // Now loop will iterate on this number.
Second Iteration
Now the number is 123, and the revs_number is 5. The while checks its condition and executes for the next iteration.
Reminder = Number % 10
Reminder = 1234 % 10 = 4
Reverse = Reverse *10+ Reminder = 5 * 10 + 4
Reverse = 50 + 4 = 54
Number = Number //10 = 12345 //10
Number = 123
Third Iteration
From the Second Iteration, the values of both Number and Reverse have been changed as: number = 123 and revs_number = 54
Reminder = Number %10
Reminder = 123%10 = 3
Reverse = Reverse *10+ Reminder = 54 * 10 + 3
Reverse = 540 + 3 = 543
Number = Number //10 = 123//10
Number = 12
Fourth Iteration
The modified number is 12 and the revs_number is 543: Now while executes again.
Reminder = Number %10
Reminder = 12 %10 = 2
Reverse = Reverse *10+ Reminder = 543 * 10 + 2
Reverse = 5430 + 2 = 5432
Number = Number //10 = 12//10
Number = 1
Fifth Iteration
Reminder = Number %10
Reminder = 1 %1 0 = 1
Reverse = Reverse *10+ Reminder = 5432 * 10 + 1
Reverse = 54320 + 1 = 54321
while loop is terminated because if found the false as a Boolean result.
You can enter the different number and check the result.
Reverse a Number Using Recursion
Let's understand the following example.
num = int(input("Enter the number: "))
revr_num = 0 # initial value is 0. It will hold the reversed number
def recur_reverse(num):
global revr_num # We can use it out of the function
if (num > 0):
Reminder = num % 10
revr_num = (revr_num * 10) + Reminder
recur_reverse(num // 10)
return revr_num
revr_num = recur_reverse(num)
print("n Reverse of entered number is = %d" % revr_num)
Output:
Enter the number: 5426
The Reverse of entered number is = 6245
Top comments (0)