Author name: Vikram Chiluka

Python List remove() Method with Examples

In the previous article, we have discussed Python List pop() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List remove() Method in Python:

The remove() method deletes the element’s first occurrence with the specified value.

Syntax:

list.remove(element)

Parameters

  • The remove() method accepts a single argument and removes it from the list.
  • If the element does not exist, a ValueError: list.remove(x): x not in list exception is thrown.

Return Value:

This function does not return any value.

Examples:

Example1:

Input:

Given List = ['hello', 'this', 'is', 'btechgeeks']
Given element to be removed = 'hello'

Output:

The given original list is: ['hello', 'this', 'is', 'btechgeeks']
The given list after removing the given element{ hello } is :
['this', 'is', 'btechgeeks']

Example2:

Input:

Given List = [-1, 0, 2, 8, 9, 2]
Given element to be removed = 2

Output:

The given original list is: [-1, 0, 2, 8, 9, 2]
The given list after removing the given element{ 2 } is :
[-1, 0, 8, 9, 2]

List remove() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Give the element to be removed as static input and store it in another variable.
  • Pass the given element as an argument to the remove() method for the given list that removes the given element from the given list.
  • Print the list after removing the given element.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks']
# Print the given original list.
print("The given original list is:", gvn_lst)
# Give the element to be removed as static input and store it in another variable.
gvn_elemnt = 'hello'
# Pass the given element as an argument to the remove() method for the
# given list that removes the given element from the given list.
gvn_lst.remove(gvn_elemnt)
# Print the list after removing the given element.
print("The given list after removing the given element{", gvn_elemnt, "} is :")
print(gvn_lst)

Output:

The given original list is: ['hello', 'this', 'is', 'btechgeeks']
The given list after removing the given element{ hello } is :
['this', 'is', 'btechgeeks']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Give the element to be removed as user input using the int(input()) function and store it in another variable.
  • Pass the given element as an argument to the remove() method for the given list that removes the given element from the given list.
  • Print the list after removing the given element.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Print the given original list.
print("The given original list is:", gvn_lst)
# Give the element to be removed as user input using the int(input()) function 
# and store it in another variable.
gvn_elemnt = int(input("Enter some random number = "))
# Pass the given element as an argument to the remove() method for the
# given list that removes the given element from the given list.
gvn_lst.remove(gvn_elemnt)
# Print the list after removing the given element.
print("The given list after removing the given element{", gvn_elemnt, "} is :")
print(gvn_lst)

Output:

Enter some random List Elements separated by spaces = -1 0 2 8 9
The given original list is: [-1, 0, 2, 8, 9]
Enter some random number = 2
The given list after removing the given element{ 2 } is :
[-1, 0, 8, 9]

Covered all examples on python concepts and missed checking out the Python List Method Examples then go with the available link & gain more knowledge about List method concepts in python.

 

Python List remove() Method with Examples Read More »

Python Tuple index() method with Examples

In the previous article, we have discussed Python Tuple count() method with Examples
Tuples in Python:

Tuples are a data structure in Python that stores an ordered succession of values. They are unchangeable. This signifies that the values of a tuple cannot be changed. They allow you to save an organized list of items. A tuple, for example, can be used to hold a list of employee names.

Tuple index() Method in Python:

The index() method returns the position in the given tuple of the given element.

Syntax:

gvntuple .index(element, start, end)

Parameter Values: 

The tuple index() method can accept up to three arguments:

element – the to-be-searched element

start (optional) – Begin searching from this index

end (optional) – Search the element all the way up to this index

Return Value:

The index() method returns the index of the specified tuple element.
A ValueError exception is thrown if the element is not found.

Note:

Only the first occurrence of the matching element is returned by the index() method.

Examples:

Example1:

Input:

Given Tuple= ('hello', 'this', 'is', 'this', 'python', 'programs')
Given Element = 'this'

Output:

The given element { this } in the given tuple ('hello', 'this', 'is', 'this', 'python', 'programs') is present at the index :
1

Example2:

Input:

Given Tuple= ('hello', 'this', 'is', 'this', 'python', 'programs')
Given Element = 'morning'

Output:

Traceback (most recent call last):
  File "/home/a3ee758dfee37d1702ad5c70e38293aa.py", line 8, in <module>
    resltind = gvntupl.index(gvnele)
ValueError: tuple.index(x): x not in tuple

Tuple index() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Example-1: If the element is present in the given Tuple

Approach:

  • Give the Tuple as the static input and store it in a variable.
  • Give the element whose index must be located in the given Tuple and store it in another variable.
  • Pass the given element to the index function for the given Tuple and store the result in resltind variable.
  • Print the resltind value.
  • The Exit of the Program.

Below is the implementation:

# Give the tuple as the static input and store it in a variable.
gvntupl = ('hello', 'this', 'is', 'this', 'python', 'programs')
# Give the element whose index must be located in the given tuple
# and store it in another variable.
gvnele = 'this'
# Pass the given element to the index function for the given tuple
# and store the result in resltind variable.
resltind = gvntupl.index(gvnele)
# Print the resltind value.
print('The given element {', gvnele, '} in the given tuple',
      gvntupl, 'is present at the index :')
print(resltind)

Output:

The given element { this } in the given tuple ('hello', 'this', 'is', 'this', 'python', 'programs') is present at the index :
1
Example-2: If the element is not present in the given Tuple

Below is the implementation:

# Give the tuple as the static input and store it in a variable.
gvntupl = ('hello', 'this', 'is', 'this', 'python', 'programs')
# Give the element whose index must be located in the given tuple
# and store it in another variable.
gvnele = 'now'
# Pass the given element to the index function for the given tuple
# and store the result in resltind variable.
resltind = gvntupl.index(gvnele)
# Print the resltind value.
print('The given element {', gvnele, '} in the given tuple',
      gvntupl, 'is present at the index :')
print(resltind)

Output:

Traceback (most recent call last):
  File "/home/a3ee758dfee37d1702ad5c70e38293aa.py", line 8, in <module>
    resltind = gvntupl.index(gvnele)
ValueError: tuple.index(x): x not in tuple
Example-3: Giving Start Index

Below is the implementation:

# Give the tuple as the static input and store it in a variable.
gvntupl = ('hello', 'this', 'is', 'this', 'python', 'programs')
# Give the element whose index must be located in the given tuple
# and store it in another variable.
gvnele = 'this'
# Pass the given element to the index function for the given tuple
# and store the result in resltind variable.
# searching the element after 1 st index by passing second argument as 1
resltind = gvntupl.index(gvnele, 1)
# Print the resltind value.
print('The given element {', gvnele, '} in the given tuple',
      gvntupl, 'is present at the index :')
print(resltind)

Output:

The given element { this } in the given tuple ('hello', 'this', 'is', 'this', 'python', 'programs') is present at the index :
1
Example-4: Giving Start and End Index

Below is the implementation:

# Give the tuple as the static input and store it in a variable.
gvntupl = ('hello', 'this', 'is', 'this', 'python', 'programs')
# Give the element whose index must be located in the given tuple
# and store it in another variable.
gvnele = 'hello'
# Pass the given element to the index function for the given tuple
# and store the result in resltind variable.
# searching the element after 1 st index to 3 index  by passing
# second argument as 1 and third argument as 3
resltind = gvntupl.index(gvnele, 1, 3)
# Print the resltind value.
print('The given element {', gvnele, '} in the given tuple',
      gvntupl, 'is present at the index :')
print(resltind)

Output:

Traceback (most recent call last):
  File "/home/0eabc1fa82ac939d529fa63ad0fd9be6.py", line 10, in <module>
    resltind = gvntupl.index(gvnele, 1, 3)
ValueError: tuple.index(x): x not in tuple

Explanation:

The element hello is present at the 0th index but not between the indices, resulting in an error.

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the Tuple as user input using tuple(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the element whose index must be located in the given Tuple as user input using the input() function and store it in another variable.
  • Pass the given element to the index function for the given Tuple and store the result in resltind variable.
  • Print the resltind value.
  • The Exit of the Program.

Below is the implementation:

# Give the Integer tuple as user input using tuple (),map(),input(),and split() functions.
# Store it in a variable.
gvntupl = tuple(map(int, input('Enter some random tuple elements = ').split()))
# Give the element as user input using the int(), input() functions,
# and store it in another variable.
gvnele = int(input('Enter some random element = '))
# Pass the given element to the index function for the given tuple
# and store the result in resltind variable.
resltind = gvntupl.index(gvnele)
# Print the resltind value.
print('The given element {', gvnele, '} in the given tuple',
      gvntupl, 'is present at the index :')
print(resltind)

Output:

Enter some random tuple elements = 4 1 7 8 3 11 7 3
Enter some random element = 3
The given element { 3 } in the given tuple (4, 1, 7, 8, 3, 11, 7, 3) is present at the index :
4

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python Tuple index() method with Examples Read More »

Python Tuple count() method with Examples

In the previous article, we have discussed Python List sort() Method with Examples
Tuples in Python:

Tuples are a data structure in Python that stores an ordered succession of values. They are unchangeable. This signifies that the values of a tuple cannot be changed. They allow you to save an organized list of items. A tuple, for example, can be used to hold a list of employee names.

Tuple count() method in Python:

The count() function returns the number of occurrences of the particular element in the given tuple.

Syntax:

giventuple.count(gvnelement)

Parameters:

The count() method only accepts one argument.

  • gvnelement: The element whose frequency is to be calculated

Return Value:

The count() method returns the number of occurrences of the given element in the given tuple.

Examples:

Example1:

Input:

Given Tuple = ('hello', 'this', 'is', 'python', 'is', 'programs')
Given Element = "is"

Output:

The count of the given element { is } in the given tuple ('hello', 'this', 'is', 'python', 'is', 'programs') is :
2

Example2:

Input:

Given tuple = (11, 44, 13, 11, 73, 11, 28, 282, 28, 19, 28, 1, 28)
Given Element = 28

Output:

The count of the given element { 28 } in the given tuple (11, 44, 13, 11, 73, 11, 28, 282, 28, 19, 28, 1, 28) is :
4

Tuple count() method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

Example-1:

String Tuple:

  • Give the string tuple as static input and store it in a variable.
  • Give the element whose frequency is to be calculated as static input and store it in another variable.
  • Pass the given element above as the argument to the count function for the given tuple and store the result in a variable say resltcnt(It has the count of the given element in the given tuple).
  • Print the value of resltcnt.
  • The Exit of the Program.

Below is the implementation:

# Give the string tuple as static input and store it in a variable.
gvntupl = ('hello', 'this', 'is', 'python', 'is', 'programs')
# Give the element whose frequency is to be calculated as static input
# and store it in another variable.
gvnelemeent = "is"
# Pass the given element above as the argument to the count function
# for the given tuple and store the result in a variable say resltcnt
# (It has the count of the given element in the given tuple).
resltcnt = gvntupl.count(gvnelemeent)
# Print the value of resltcnt.
print('The count of the given element {', gvnelemeent,
      '} in the given tuple', gvntupl, 'is :')
print(resltcnt)

Output:

The count of the given element { is } in the given tuple ('hello', 'this', 'is', 'python', 'is', 'programs') is :
2

Example-2:

Integer Tuple:

  • Give the Integer tuple as static input and store it in a variable.
  • Give the element whose frequency is to be calculated as static input and store it in another variable.
  • Pass the given element above as the argument to the count function for the given tuple and store the result in a variable say resltcnt(It has the count of the given element in the given tuple).
  • Print the value of resltcnt.
  • The Exit of the Program.

Below is the implementation:

# Give the Integer tuple as static input and store it in a variable.
gvntupl = (11, 44, 13, 11, 73, 11, 28, 282, 28, 19, 28, 1, 28)
# Give the element whose frequency is to be calculated as static input
# and store it in another variable.
gvnelemeent = 28
# Pass the given element above as the argument to the count function
# for the given tuple and store the result in a variable say resltcnt
# (It has the count of the given element in the given tuple).
resltcnt = gvntupl.count(gvnelemeent)
# Print the value of resltcnt.
print('The count of the given element {', gvnelemeent,
      '} in the given tuple', gvntupl, 'is :')
print(resltcnt)

Output:

The count of the given element { 28 } in the given tuple (11, 44, 13, 11, 73, 11, 28, 282, 28, 19, 28, 1, 28) is :
4

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the Integer tuple as user input using tuple (),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the element as user input using the int(), input() functions, and store it in another variable.
  • Pass the given element above as the argument to the count function for the given tuple and store the result in a variable say resltcnt(It has the count of the given element in the given tuple).
  • Print the value of resltcnt.
  • The Exit of Program.

Below is the implementation:

# Give the Integer tuple as user input using tuple (),map(),input(),and split() functions.
# Store it in a variable.
gvntupl = tuple(map(int, input('Enter some random tuple elements = ').split()))
# Give the element as user input using the int(), input() functions,
# and store it in another variable.
gvnelemeent = int(input('Enter some random element = '))
# Pass the given element above as the argument to the count function
# for the given tuple and store the result in a variable say resltcnt
# (It has the count of the given element in the given tuple).
resltcnt = gvntupl.count(gvnelemeent)
# Print the value of resltcnt.
print('The count of the given element {', gvnelemeent,
      '} in the given tuple', gvntupl, 'is :')
print(resltcnt)

Output:

Enter some random tuple elements = 12 7 1 8 3 2 1 7 1 1
Enter some random element = 1
The count of the given element { 1 } in the given tuple (12, 7, 1, 8, 3, 2, 1, 7, 1, 1) is :
4

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python Tuple count() method with Examples Read More »

Python List sort() Method with Examples

In the previous article, we have discussed Python List reverse() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List sort() Method in Python:

The sort() method sorts the elements of a list in ascending or descending order.

By default, the sort() method ascends the list.

Syntax:

list.sort(key=...., reverse=....)

Alternatively, you can use Python’s built-in sorted() function to accomplish the same thing.

sorted(list, key=...., reverse=....)

Note: The most basic distinction between sort() and sorted() is that sort() changes the list directly and returns no value, whereas sorted() does not change the list and returns the sorted list.

Parameter Values of sort():

Sort() does not require any additional parameters by default. It does, however, have two optional parameters:

  • reverse: This is Optional. The list will be sorted descending if reverse=True is set. The default value is reverse=False.
  • key: This is Optional. A function that allows you to specify the sorting criteria (s)

Return Value:

The sort() method produces no output. Instead, it modifies the original list.

Use sorted if you want a function to return the sorted list rather than change the original list ().

Examples:

Example1:

Input:

Given List = ['g', 'r', 'c', 'x', 'e']

Output:

The Given original list is : ['g', 'r', 'c', 'x', 'e']
The given list after sorting in ascending order:  ['c', 'e', 'g', 'r', 'x']

Example2:

Input:

Given List = ['hello', 'this', 'is', 'btechgeeks']

Output:

The Given original list is : ['hello', 'this', 'is', 'btechgeeks']
The given list after sorting in descending order: 
['this', 'is', 'hello', 'btechgeeks']

List sort() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

1) sort in Ascending Order

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list to sort the given list elements in ascending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['g', 'r', 'c', 'x', 'e']
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list to sort the given list elements in
# ascending order.
gvn_lst.sort()
# Print the list after sorting all its elements in ascending order.
print("The given list after sorting in ascending order: ", gvn_lst)

Output:

The Given original list is : ['g', 'r', 'c', 'x', 'e']
The given list after sorting in ascending order:  ['c', 'e', 'g', 'r', 'x']
2) sort in Descending Order

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list by passing the argument as reverse = “True” to sort the given list elements in descending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "btechgeeks"]
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list by passing the argument as
# reverse = "True" to sort the given list elements in descending order.
gvn_lst.sort(reverse=True)
# Print the list after sorting all its elements in descending order.
print("The given list after sorting in descending order: ")
print(gvn_lst)

Output:

The Given original list is : ['hello', 'this', 'is', 'btechgeeks']
The given list after sorting in descending order: 
['this', 'is', 'hello', 'btechgeeks']
3)Sort with custom function using key

If you want to create your own sorting implementation, the sort() method accepts a key function as an optional parameter.

You can sort the given list based on the results of the key function.

list.sort(key=len)

Below is the implementation:

# Taking element to sort
def givenelement(element):
    return element[0]


# Give the list as static input and store it in a variable.
gvn_lst = [(1, 3), (4, 6), (2, 6), (5, 1)]
# sort the given list with the key
gvn_lst.sort(key=givenelement)
# print the given list
print('The given list after Sorting:', gvn_lst)

Output:

The given list after Sorting: [(1, 3), (2, 6), (4, 6), (5, 1)]

Method #2: Using Built-in Functions (User Input)

1) sort in Ascending Order

Approach:

  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list to sort the given list elements in ascending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(input("Enter some random List Elements separated by spaces = ").split())
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list to sort the given list elements in
# ascending order.
gvn_lst.sort()
# Print the list after sorting all its elements in ascending order.
print("The given list after sorting in ascending order: ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = A R Q D I
The Given original list is : ['A', 'R', 'Q', 'D', 'I']
The given list after sorting in ascending order: ['A', 'D', 'I', 'Q', 'R']
2) sort in Descending Order

Approach:

  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list by passing the argument as reverse = “True” to sort the given list elements in descending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(input("Enter some random List Elements separated by spaces = ").split())
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list by passing the argument as
# reverse = "True" to sort the given list elements in descending order.
gvn_lst.sort(reverse=True)
# Print the list after sorting all its elements in descending order.
print("The given list after sorting in descending order: ")
print(gvn_lst)

Output:

Enter some random List Elements separated by spaces = good morning btechgeeks hello all
The Given original list is : ['good', 'morning', 'btechgeeks', 'hello', 'all']
The given list after sorting in descending order: 
['morning', 'hello', 'good', 'btechgeeks', 'all']

Covered all examples on python concepts and missed checking out the Python List Method Examples then go with the available link & gain more knowledge about List method concepts in python.

Python List sort() Method with Examples Read More »

Python List reverse() Method with Examples

In the previous article, we have discussed Python List remove() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List reverse() Method in Python:

The reverse() method reverses the list’s elements.

Syntax:

list.reverse()

Parameters: This function has no parameters.

Return Value:

The reverse() method produces no output. It is used to update the existing list.

Examples:

Example1:

Input:

Given List = ['welcome', 'to', 'Python', 'programs']

Output:

The given original list: ['welcome', 'to', 'Python', 'programs']
The given list after reversing :  ['programs', 'Python', 'to', 'welcome']

Example2:

Input:

Given List = [10, 20, 30, 40, 50]

Output:

The given original list: [10, 20, 30, 40, 50]
The given list after reversing :  [50, 40, 30, 20, 10]

List reverse() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Apply reverse() function to the given list that reverses all the elements of the given list.
  • Print the list after reversing all its elements.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["welcome", "to", "Python", "programs"]
# Print the given original list.
print("The given original list:", gvn_lst)
# Apply reverse() function to the given list that reverses all the elements of
# the given list.
gvn_lst.reverse()
# Print the list after reversing all its elements.
print("The given list after reversing : ", gvn_lst)

Output:

The given original list: ['welcome', 'to', 'Python', 'programs']
The given list after reversing :  ['programs', 'Python', 'to', 'welcome']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Apply reverse() function to the given list that reverses all the elements of the given list.
  • Print the list after reversing all its elements.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Print the given original list.
print("The given original list:", gvn_lst)
# Apply reverse() function to the given list that reverses all the elements of
# the given list.
gvn_lst.reverse()
# Print the list after reversing all its elements.
print("The given list after reversing : ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40 50
The given original list: [10, 20, 30, 40, 50]
The given list after reversing : [50, 40, 30, 20, 10]

Reversing a list Using Slicing Operator

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Reverse the elements of the given list using the slicing operator and store it in another variable.
  • Print the list after reversing all its elements.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks', 25, 35]
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Reverse the elements of the given list using the slicing operator and
# store it in another variable.
reversee_lst = gvn_lst[::-1]
# Print the list after reversing all its elements.
print("The given list after reversing : ", reversee_lst)

Output:

The Given original list is : ['good', 'morning', 'btechgeeks', 25, 35]
The given list after reversing :  [35, 25, 'btechgeeks', 'morning', 'good']

Covered all examples on python concepts and missed checking out the Python List Method Examples then go with the available link & gain more knowledge about List method concepts in python.

Python List reverse() Method with Examples Read More »

Python List pop() Method with Examples

In the previous article, we have discussed Python List insert() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List pop() Method in Python:

The pop() method removes the item at the specified index from the list and returns the item that was removed.

Note: By default, it removes the last element from the list.

Syntax:

list.pop(index)

Parameters

The pop() method only accepts one argument (index).

index: This is optional.

  • It is not required to pass an argument to the method. If no argument is provided, the default index -1 is used (index of the last item).
  • If the index passed to the method is not within the range, the IndexError: pop index out of range exception is thrown.

Return Value:

The pop() method returns the item at the specified index. This item has been removed from the list as well.

Examples:

Example1:

Input:

Given list = ['good', 'morning', 'btechgeeks', 4, 5, 6]
Given index = 2

Output:

The value returned is:  btechgeeks
The given list after poping 2 item =  ['good', 'morning', 4, 5, 6]

Example2:

Input:

Given list = ['hello', 'this', 'is', 'btechgeeks']

Output:

The value returned is:  btechgeeks
The given list after poping with giving an index is : ['hello', 'this', 'is']

List pop() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number(index) as static input and store it in another variable.
  • Pass the given index as a parameter to the pop() function for the given list (which removes the element at the given index and returns the value that is removed).
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after poping the item at the given index value.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks', 4, 5, 6]
# Give the number(index) as static input and store it in another variable.
gvn_indx = 2
# Pass the given index as a parameter to the pop() function for the given
# list (which removes the element at the given index and returns the value
# that is removed).
# Store it in another variable.
retrnvalu = gvn_lst.pop(gvn_indx)
# Print the above-returned value.
print("The value returned is: ", retrnvalu)
# Print the given list after poping the item at the given index value.
print("The given list after poping", gvn_indx, "item = ", gvn_lst)

Output:

The value returned is:  btechgeeks
The given list after poping 2 item =  ['good', 'morning', 4, 5, 6]

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the number(index) as user input using the int(input()) function and store it in another variable.
  • Pass the given index as a parameter to the pop() function for the given list (which removes the element at the given index and returns the value that is removed).
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after poping the item at the given index value.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the number(index) as user input using the int(input()) function 
# and store it in another variable.
gvn_indx = int(input("Enter some random number = "))
# Pass the given index as a parameter to the pop() function for the given
# list (which removes the element at the given index and returns the value
# that is removed).
# Store it in another variable.
retrnvalu = gvn_lst.pop(gvn_indx)
# Print the above-returned value.
print("The value returned is: ", retrnvalu)
# Print the given list after poping the item at the given index value.
print("The given list after poping", gvn_indx, "item = ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 25 60 56 13 12
Enter some random number = 3
The value returned is: 13
The given list after poping 3 item = [25, 60, 56, 12]

Similarly, pop without an index and negative index

Approach:

  • Give the list as static input and store it in a variable.
  • Give the negative number(index) as static input and store it in another variable.
  • Pass the given index as a parameter to the pop() function for the given list (which removes the element at the given index and returns the value that is removed).
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after poping the item at the given index value.
  • Apply the pop() function to the given list without giving an index and get the value that is returned.
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after applying the pop() function.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks']
# Give the negative number(index) as static input and store it in
# another variable.
gvn_indx = -3
# Pass the given index as a parameter to the pop() function for the given
# list (which removes the element at the given index and returns the value
# that is removed).
# Store it in another variable.
retrnvalu = gvn_lst.pop(gvn_indx)
# Print the above-returned value.
print("The value returned is: ", retrnvalu)
# Print the given list after poping the item at the given index value.
print("The given list after poping", gvn_indx, "item = ", gvn_lst)
# Apply pop() function to the given list without giving an index and get the
# value that is returned.
# Store it in another variable.
retrnvalu1 = gvn_lst.pop()
# Print the above-returned value.
print("The value returned is: ", retrnvalu1)
# Print the given list after applying pop() function
print("The given list is after applying pop() function:", gvn_lst)

Output:

The value returned is:  this
The given list after poping -3 item =  ['hello', 'is', 'btechgeeks']
The value returned is:  btechgeeks
The given list is after applying pop() function: ['hello', 'is']

Know about the syntax and usage of functions to manipulate lists with the provided Python List Method Examples and use them.

Python List pop() Method with Examples Read More »

Python List insert() Method with Examples

In the previous article, we have discussed Python List copy() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List insert() Method in Python:

Inserts the specified value at the specified position using the insert() method.

Syntax:

list.insert(position, element)

Parameters

position: This is Required. A number indicating where the value should be inserted.

element: This is Required. Any type of element (string, number, object etc.)

Return Value:

The insert() method produces no results; it returns None. It only makes changes to the current list.

Examples:

Example1:

Input:

Given List = ["hello", "is", "btechgeeks"]
Given position = 1
Given element = "this"

Output:

The given list after inserting the given element: 
['hello', 'this', 'is', 'btechgeeks']

Example2:

Input:

Given List = ["good", "morning", "btechgeeks"]
Given position = 1
Given Tuple = (1, 3, 5, 7)

Output:

The given list after inserting the given Tuple: 
['good', (1, 3, 5, 7), 'morning', 'btechgeeks']

List insert() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

1) Inserting an element to the List

Approach:

  • Give the list as static input and store it in a variable.
  • Give the position as static input and store it in another variable.
  • Give the element as static input and store it in another variable.
  • Pass the given position and given element as arguments to the insert() function for the given list to insert the given element at the given position.
  • Print the given list after inserting the given element.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "is", "btechgeeks"]
# Give the position as static input and store it in another variable.
gvn_positin = 1
# Give the element as static input and store it in another variable.
gvn_elemnt = "this"
# Pass the given position and given element as arguments to the insert()
# function for the given list to insert the given element at the given position.
gvn_lst.insert(gvn_positin, gvn_elemnt)
# Print the given list after inserting the given element.
print("The given list after inserting the given element: ")
print(gvn_lst)

Output:

The given list after inserting the given element: 
['hello', 'this', 'is', 'btechgeeks']
2)Inserting tuple as an element to the List

Approach:

  • Give the list as static input and store it in a variable.
  • Give the position as static input and store it in another variable.
  • Give the tuple as static input and store it in another variable.
  • Pass the given position and given tuple as arguments to the insert() function for the given list to insert the given tuple at the given position.
  • Print the given list after inserting the given tuple.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["good", "morning", "btechgeeks"]
# Give the position as static input and store it in another variable.
gvn_positin = 1
# Give the tuple as static input and store it in another variable.
gvn_tupl = (1, 3, 5, 7)
# Pass the given position and given tuple as arguments to the insert()
# function for the given list to insert the given tuple at the given position.
gvn_lst.insert(gvn_positin, gvn_tupl)
# Print the given list after inserting the given Tuple.
print("The given list after inserting the given Tuple: ")
print(gvn_lst)

Output:

The given list after inserting the given Tuple: 
['good', (1, 3, 5, 7), 'morning', 'btechgeeks']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the position as user input using the int(input()) function and store it in another variable.
  • Give the element as user input using the input() function and store it in another variable.
  • Pass the given position and given element as arguments to the insert() function for the given list to insert the given element at the given position.
  • Print the given list after inserting the given element.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the position as user input using the int(input()) function and 
# store it in another variable.
gvn_positin = int(input("Enter some random number = "))
# Give the element as user input using the input() function and 
# store it in another variable.
gvn_elemnt = input("Enter some random string = ")
# Pass the given position and given element as arguments to the insert()
# function for the given list to insert the given element at the given position.
gvn_lst.insert(gvn_positin, gvn_elemnt)
# Print the given list after inserting the given element.
print("The given list after inserting the given element: ")
print(gvn_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40 70
Enter some random number = 2
Enter some random string = hello
The given list after inserting the given element: 
[10, 20, 'hello', 30, 40, 70]

Know about the syntax and usage of functions to manipulate lists with the provided Python List Method Examples and use them.

Python List insert() Method with Examples Read More »

Python help() function with Examples | Help function in Python

In the previous article, we have discussed Python String encode() Method with Examples
help() Function in Python:

The help() method invokes or calls Python’s built-in help system.

The Python help function displays documentation for modules, functions, classes, keywords, and so on.

Syntax:

help(object)

Parameters

The help() method only accepts one parameter.

object: This is optional. you want to generate help and support from the given object

For interactive use, the help() method is used. When you need assistance writing Python programs and using Python modules, it is recommended that you try it in your interpreter.

1)Note: It should be noted that object is passed to help() (not a string)

For Example:

Input:

help(list)

Output:

Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

Explanation:

In this way we get the output which displays the documentation for modules, 
functions, classes, keywords, and so on.

similarly, try out for these

>>help(dict)
>>help(print)
>>help(tuple)
>>help([4,5,6])

If a string is passed as an argument, the name of a module, function, class, method, keyword, or documentation topic is printed, as well as a help page.

2)Note: It should be noted that string is passed as an argument to help()

When a string is passed as an argument, it is looked up as the name of a module, function, class, method, keyword, or documentation topic and a help page is printed.

Check it out for the following Examples.

Input:

help('hello')

Output:

No Python documentation found for 'hello'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

similarly, try out for these

>>help('print')
>>help('uvw')

Input:

from math import * 
help('math.pow')

Output:

Help on built-in function pow in math:

math.pow = pow(...)
    pow(x, y)
    
    Return x**y (x to the power of y).

3)Note: It should be noted that no argument is passed to help()

If no arguments are provided, Python’s help utility (interactive help system) is launched on the console.

>>help()

Then, enter the topic name to get help with writing Python programmes and using Python modules.

As an example, Check it out for the following Examples:

help > True
help > 'print'
help > print

To return to the interpreter and exit the help utility, type quit and press enter.

help > quit

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python help() function with Examples | Help function in Python Read More »

Python String splitlines() Method with Examples

In the previous article, we have discussed Python String maketrans() Method with Examples
splitlines() Method in Python:

The splitlines() method divides(splits) a string into a list of lines. Line breaks are used for splitting.

Syntax:

string.splitlines(keeplinebreaks)

Parameters

keeplinebreaks: Optional. Specifies whether or not line breaks should be included (True) (False). False is the default value.

Return Value: 

splitlines() returns a list of the string’s lines.

If no line break characters are present, it returns a list with a single item (a single line).

splitlines() divides lines at the following points:

  • \n – Line Feed
  • \r – Carriage Return
  • \r\n – Carriage Return + Line Feed
  • \v or \x0b – Line Tabulation
  • \f or \x0c – Form Feed
  • \x1c – File Separator
  • \x1d – Group Separator
  • \x1e – Record Separator
  • \x85 – Next Line (C1 Control Code)
  • \u2028 – Line Separator
  • \u2029 – Paragraph Separator

Examples:

Example1:

Input:

Given string = 'welcome to\n Python\n programs\n'

Output:

The given string after spliting : ['welcome to', ' Python', ' programs']

Example2:

Input:

Given string = 'hello all good morning'

Output:

The given string after spliting : ['hello all good morning']

Example3:

Input:

Given string = 'welcome to\n Python\n programs\n'

Output:

The given string after spliting by passing the true parameter:
['welcome to\n', ' Python\n', ' programs\n']

String splitlines() Method Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Apply splitlines() function to the given string that divides(splits) a given string into a list of lines.
  • Store it in another variable.
  • Print the result after splitting the given string.
  • Apply splitlines() function to the given string by passing the parameter as True and printing the result.
  • Give the second string as static input and store it in a variable.
  • Apply splitlines() function to the given second string and print the result.
  • The Exit of Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'welcome to\n Python\n programs\n'
# Apply splitlines() function to the given string that divides(splits) a
# given string into a list of lines.
# Store it in another variable.
splt_str = gvn_str.splitlines()
# Print the result after splitting the given string.
print("The given string after spliting :", splt_str)
# Apply splitlines() function to the given string by passing the parameter
# as True and printing the result.
print("The given string after spliting :", gvn_str.splitlines(True))
# Give the second string as static input and store it in a variable.
gvn_scndstr = 'hello all good morning'
# Apply splitlines() function to the given second string and print the result.
print("The given string after spliting :", gvn_scndstr.splitlines())

Output:

The given string after spliting : ['welcome to', ' Python', ' programs']
The given string after spliting : ['welcome to\n', ' Python\n', ' programs\n']
The given string after spliting : ['hello all good morning']

Go through our tutorial and learn about various Python String Method Examples and learn how to apply the knowledge while dealing with strings.

Python String splitlines() Method with Examples Read More »

Python String encode() Method with Examples

In the previous article, we have discussed Python Program for Pass Statement with Examples
String encode() Method in Python:

The encode() method encodes the string using the encoding specified. When no encoding is specified, UTF-8 is used.

Syntax:

string.encode(encoding=encoding, errors=errors)

Parameter Values:

encoding: This is Optional. A String indicating the encoding to be used. UTF-8 is the default.

errors: This is Optional. The error method is specified as a String. The following are legal values:

  • backslashreplace – employs a backslash in place of the unencoded character
  • ignore – does not encode characters that cannot be encoded.
  • namereplace – replaces the character with text that describes the character.
  • strict – On failure, the default raises an error.
  • replace – inserts a question mark in place of the character.
  • xmlcharrefreplace – a character is replaced with an xml character.

Examples:

Example1:

Input:

Given string =  "Welcome to Pythön-prögrams"

Output:

b'Welcome to Pyth\\xf6n-pr\\xf6grams'
b'Welcome to Pythn-prgrams'
b'Welcome to Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n-pr\\N{LATIN SMALL LETTER O WITH DIAERESIS}grams'
b'Welcome to Pyth?n-pr?grams'
b'Welcome to Pyth&#246;n-pr&#246;grams'

Example2:

Input:

Given string = "Hello this is vikråm"

Output:

b'Hello this is vikr\\xe5m'
b'Hello this is vikrm'
b'Hello this is vikr\\N{LATIN SMALL LETTER A WITH RING ABOVE}m'
b'Hello this is vikr?m'
b'Hello this is vikr&#229;m'

String encode() Method Examples in Python

Method #1: Using Built-in Functions (Static Input)

These examples demonstrate the use of ascii encoding and a character that cannot be encoded, with various errors:

Approach:

  • Give the string as static input() and store it in a variable.
  • Give the encoding value as ascii and errors as “backslashreplace” for the given string using the encode function and print it.
  • Here “backslashreplace” employs a backslash in place of the unencoded character.
  • Give the encoding value as ascii and errors as “ignore” for the given string using the encode function and print it.
  • Here “ignore” does not encode characters that cannot be encoded.
  • Give the encoding value as ascii and errors as “namereplace” for the given string using the encode function and print it.
  • Here “namereplace” replaces the character with text that describes the character.
  • Give the encoding value as ascii and errors as “replace” for the given string using the encode function and print it.
  • Here “replace” inserts a question mark in place of the character.
  • Give the encoding value as ascii and errors as “xmlcharrefreplace” for the given string using the encode function and print it.
  • Here “xmlcharrefreplace” is replacing a character with an xml character.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input() and store it in a variable.
gvn_str = "Welcome to Pythön-prögrams"
# Give the encoding value as ascii and errors as "backslashreplace" for the
# given string using the encode function and print it.
# Here "backslashreplace" employs a backslash in place of the unencoded character.
print(gvn_str.encode(encoding="ascii", errors="backslashreplace"))
# Give the encoding value as ascii and errors as "ignore" for the given
# string using the encode function and print it.
# Here "ignore" does not encode characters that cannot be encoded.
print(gvn_str.encode(encoding="ascii", errors="ignore"))
# Give the encoding value as ascii and errors as "namereplace" for the given
# string using the encode function and print it.
# Here "namereplace" replaces the character with text that describes the character.
print(gvn_str.encode(encoding="ascii", errors="namereplace"))
# Give the encoding value as ascii and errors as "replace" for the given
# string using the encode function and print it.
# Here "replace" inserts a question mark in place of the character.
print(gvn_str.encode(encoding="ascii", errors="replace"))
# Give the encoding value as ascii and errors as "xmlcharrefreplace" for the
# given string using the encode function and print it.
# Here "xmlcharrefreplace" is replacing a character with an xml character.
print(gvn_str.encode(encoding="ascii", errors="xmlcharrefreplace"))

Output:

b'Welcome to Pyth\\xf6n-pr\\xf6grams'
b'Welcome to Pythn-prgrams'
b'Welcome to Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n-pr\\N{LATIN SMALL LETTER O WITH DIAERESIS}grams'
b'Welcome to Pyth?n-pr?grams'
b'Welcome to Pyth&#246;n-pr&#246;grams'

Method #2: UTF-8 encoding to the given string (Static Input)

Below is the implementation:

gvn_str = "Hello this is vikråm"
rslt = gvn_str.encode()
print(rslt)

Output:

b'Hello this is vikr\xc3\xa5m'

String Encoding:

Strings have been stored as Unicode since Python 3.0, which means that each character in the string is represented by a code point. As a result, each string is simply a series of Unicode code points.

The sequence of code points is converted into a set of bytes for efficient storage of these strings. Encoding is the name given to this process.

There are numerous encodings available, each of which treats a string differently. Popular encodings include utf-8, ascii, and others.

Using the string encode() method, you can convert unicode strings to any Python encoding. Python’s default encoding is utf-8.

Go through our tutorial and learn about various Python String Method Examples and learn how to apply the knowledge while dealing with strings.

 

Python String encode() Method with Examples Read More »