Python Functions https://www.skillvertex.com/blog Thu, 11 Apr 2024 12:02:28 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png Python Functions https://www.skillvertex.com/blog 32 32 Python String Methods https://www.skillvertex.com/blog/python-string-methods/ https://www.skillvertex.com/blog/python-string-methods/#respond Thu, 11 Apr 2024 12:02:28 +0000 https://www.skillvertex.com/blog/?p=7928 Read more]]>

Table of Contents

Python String Methods

Python consists of built-in methods that will be used on the strings. They will manipulate the strings. However, the string method won’t change the original string instead it will return the new string along with the changed attributes. Let us look into this article to learn more about Python String Methods.

What is Python String?

Python string consists of the sequence of the Unicode characters that will be enclosed in the quotation marks. Hence, you can find Python string methods below.

What are the Python String Methods?

Python functions will change the case of the strings. Check out the Python String Methods provided below:

a. lower()-It will convert all the uppercase characters in a string to the lowercase.

b.upper(): This string method in Python will turn all the lowercase characters in a string into the uppercase.

c.title(): It will change the string to the title case.

d.swapcase(): It will swap the cases of all the characters in the string.

e.capitalize(): capitalize will convert the first character of the string to the uppercase.

List of Python String Methods

Let us look into the table below to learn more about the Python String Methods list.

Function Name Description
capitalize()Capitalize will Change the first character of the string to a capital (uppercase) letter.
center()This string method will pad the string with the specified character.
casefold()It will implement careless string matching.
encode()encount will encode the string with the particular encoded scheme.
count()This string method in Python will return the number of occurrences of the substring in the string.
endswith()This find() will return the lowest index of the substring if it is found
expandtabs()This string method will Specify the amount of space to be substituted with the “\t” symbol in the string.
find()This find() will returns the lowest index of the substring if it is found
format()This string method will format the string for printing it to the console.
format_map()It will format the specified value in the strings with the dictionary.
index()Format specified values in a string using a dictionary.
isalnum()This string method will Check if all the characters in a given string are either alphanumeric or not.
isalpha()isalpha() will returns “True” if all characters in the string are alphabet.
isdecimal()isdecimal() will return true if every characters in a string are decimal
isdigit()It will returns “True” if all characters in the string are digits
isidentifier()It will Check whether a string is a valid identifier or not
islower()islower() will check if all characters in the string are lowercase.
isnumeric()Isnumeric will return “True” when the string characters are numeric.
isprintable()It will returns “True” when the characters in the string are either printable or the string is empty
isspace()isspace() will Returns “True” if all characters in the string are whitespace characters
istitle()It will return “True” if the string is title-cased.
isupper()It will check if all the characters in the string are uppercase.
join()Join() will return a concatenated String.
ljust()It will the left align with the string according to the width provided.
lower()lower() will change all the uppercase characters in a string into lowercase.
lstrip()It will return the string with the leading characters that need to be removed.
maketrans()Replace all occurrences of a substring with another substring
partition()Splits the string at the first occurrence of the separator 
replace()This Python String Method will replace all occurrences of a substring with another substring.
rfind()It will return the highest index of the substring.
rindex()This rindex() will return with the highest index of the substring inside the string.
rjust()This will right align the string according to the width required.
rpartition()This string method will split the given string into three parts.
rsplit()Split the string from the right by the specified separator
rstrip()r strip() will remove the trailing characters
splitlines()This splitlines() will split the lines at line boundaries.
startswith()This method will return “True” if the string begins with the given prefix.
strip()It will return the string with both the leading and trailing characters.
swapcase()Converts all uppercase characters to lowercase and vice versa
title()This will Convert string to title case
translate()translate () will modify the string according to the given translation mappings
upper()It will turn every lowercase character in a string into an uppercase
zfill()It will return a copy of the string with ‘0’ characters padded to the left side of the string

What are the examples for changing the Cases of Python Strings?

Example

Let us look into the example provided below for changing the case of the Python string.

# Define a sample string
sample_string = "Hello, World!"

# 1. len(): Get the length of the string
length = len(sample_string)
print(f"Length of the string: {length}")

# 2. upper(): Convert the string to uppercase
uppercase_string = sample_string.upper()
print(f"Uppercase string: {uppercase_string}")

# 3. lower(): Convert the string to lowercase
lowercase_string = sample_string.lower()
print(f"Lowercase string: {lowercase_string}")

# 4. capitalize(): Capitalize the first character of the string
capitalized_string = sample_string.capitalize()
print(f"Capitalized string: {capitalized_string}")

# 5. count(): Count the occurrences of a substring in the string
substring_count = sample_string.count("l")
print(f"Count of 'l' in the string: {substring_count}")

# 6. replace(): Replace a substring with another substring
replaced_string = sample_string.replace("Hello", "Hi")
print(f"String after replacement: {replaced_string}")

# 7. split(): Split the string into a list of substrings based on a delimiter
split_string = sample_string.split(",")
print(f"String after split: {split_string}")

# 8. strip(): Remove leading and trailing whitespaces from the string
whitespace_string = "    Hello, World!    "
stripped_string = whitespace_string.strip()
print(f"String after stripping whitespaces: {stripped_string}")

Output

Length of the string: 13
Uppercase string: HELLO, WORLD!
Lowercase string: hello, world!
Capitalized string: Hello, world!
Count of 'l' in the string: 3
String after replacement: Hi, World!
String after split: ['Hello', ' World!']
String after stripping whitespaces: Hello, World!

Conclusion

To conclude, a Python string is a sequence of characters enclosed by quotation marks. This article has also listed the various Python string methods and will help the students to improve their knowledge and skills in Python String Methods.

Python String Method- FAQs

Q1. What is a string method in Python?

Ans. This Python string method consists of the in-built Python function that will be performed on the lists.

Q2. What is __ str __ in Python?

Ans. The _str_ method will return the human-readable, informal, or string representation of this method.

Q3.What is a string-to-string method?

Ans. The string-to-string method is an in-built method in Java that will return the value that is provided to the string object.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-string-methods/feed/ 0
Python – Sets https://www.skillvertex.com/blog/python-sets/ https://www.skillvertex.com/blog/python-sets/#respond Wed, 20 Mar 2024 06:27:43 +0000 https://www.skillvertex.com/blog/?p=8332 Read more]]>

Table of Contents

Python – Sets

The set is one of the built-in data types in Python. Read this article to learn more about the Python Sets.

However, in mathematics, a set is the collection of data types including a list or tuple. A set object consists of a collection of one or more immutable objects that will be enclosed by the curly brackets{}.

What is Set in Python?

The Python set will allow you to store multiple items in a single variable. Thus, the set is among the 4 built-in data types in Python that will store the collection of data.

Furthermore, the Python set will indicate an unordered, unchangeable, and unindexed collection. It won’t allow any duplicate values. In simple terms, unordered will refer to the items with no defined order in the Python sets. So, it will show in a different order each time you need to use them and won’t be referred by the index or key. The set items are unchangeable.

What are the examples of Python sets?

Let us look into examples of Python sets provided below:

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Output: Elements of set1
print("Set 1:", set1)

# Output: Elements of set2
print("Set 2:", set2)

# Adding an element to set1
set1.add(6)
# Output: Updated set1
print("After adding 6 to set 1:", set1)

# Removing an element from set2
set2.remove(8)
# Output: Updated set2
print("After removing 8 from set 2:", set2)

# Union of set1 and set2
union_set = set1.union(set2)
# Output: Union of set1 and set2
print("Union of set1 and set2:", union_set)

# Intersection of set1 and set2
intersection_set = set1.intersection(set2)
# Output: Intersection of set1 and set2
print("Intersection of set1 and set2:", intersection_set)

# Difference between set1 and set2
difference_set = set1.difference(set2)
# Output: Difference between set1 and set2
print("Difference of set1 and set2:", difference_set)

# Checking if set1 is a subset of set2
is_subset = set1.issubset(set2)
# Output: Whether set1 is a subset of set2
print("Is set1 a subset of set2:", is_subset)

Output

Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
After adding 6 to set 1: {1, 2, 3, 4, 5, 6}
After removing 8 from set 2: {4, 5, 6, 7}
Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7}
Intersection of set1 and set2: {4, 5, 6}
Difference of set1 and set2: {1, 2, 3}
Is set1 a subset of set2: False

Example 2 – to illustrate that the duplicates are not allowed in Python sets

# Creating a set with duplicate elements
my_set = {1, 2, 3, 3, 4, 4, 5}

# Output: The set with duplicates
print("Set with duplicates:", my_set)

Output

Set with duplicates: {1, 2, 3, 4, 5}

Example 3- to determine the length of Python sets

Check out the example below to determine the length of Python sets

# Creating a set
my_set = {1, 2, 3, 4, 5}

# Getting the length of the set
set_length = len(my_set)

# Output: Length of the set
print("Length of the set:", set_length)

Output

Length of the set: 5

Example 4- to create the Python set with items of different data types

# Creating a set with items of different data types
mixed_set = {1, 2.5, 'apple', (3, 4)}

# Output: The set with different data types
print("Set with different data types:", mixed_set)

Output

Set with different data types: {1, 2.5, 'apple', (3, 4)}

What is the Set() Constructor?

The Set() constructor will help you to create the Python sets.

What is the example for a set constructor?

# Creating a set using the set constructor
my_set = set([1, 2, 3, 4, 5])

# Output: The created set
print("Created set using set constructor:", my_set)

Output

Created set using set constructor: {1, 2, 3, 4, 5}

Conclusion

In Python, sets are a powerful data structure that stores unique elements. They’re like lists, but they don’t allow duplicates. Sets are defined using curly braces {}, and you can create a set using either curly braces directly or the set() constructor.

Hence, a set will allow you to perform various operations with sets like adding elements, removing elements, finding intersections, unions, and differences, and checking for subsets.

Python – Sets – FAQs

Q1.What is set and subset in Python?

Ans. A subset indicates the collection of elements that will belong to another set. In contrast, the set is the collection of data types.

Q2.Are Python sets unique?

Ans. Yes, set elements are unique

Q3.Is set a class in Python?

Ans. Yes, in Python, a set is a built-in data type and is an unordered collection of unique elements. It is implemented as a class in Python.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-sets/feed/ 0
Python Update Tuples https://www.skillvertex.com/blog/python-update-tuples/ https://www.skillvertex.com/blog/python-update-tuples/#respond Tue, 19 Mar 2024 06:55:29 +0000 https://www.skillvertex.com/blog/?p=8179 Read more]]>

Table of Contents

Python Update Tuples

Python is versatile and is known as a powerful programming language. It will also provide rich data structures for monitoring several types of information. Check out this article to learn more about the Python Update Tuples.

Whereas, tuples are ordered collections with unique characteristics. Tuples are immutable and once the meaning is made, it can’t be altered.

What is Tuple in Python?

In Python, A tuple is referred to as an ordered, immutable sequence of elements. It also has a data structure that will allow you to store the multiple values of different types together.

Furthermore, tuples will work similarly to the list in Python. In the syntax of tuples, it will consist of elements that are surrounded by the parenthesis() and are separated with commas.

How do you change the Tuple Values in Python?

Check out the example to learn how to convert the tuple into the list.

# Original tuple
x = ("apple", "banana", "cherry")

# Convert tuple to list
y = list(x)

# Replace the second element of the list with 'mango'
y[1] = 'mango'

# Display the converted list
print("Original Tuple:")
print(x)
print("\nConverted List:")
print(y)

Output

Original Tuple:
('apple', 'banana', 'cherry')

Converted List:
['apple', 'mango', 'cherry']

What are the Several ways to add the item to the Python Tuple?

In Python, tuples are mostly immutable and do not have a built-in append() method. Some of the ways to add the items to the tuple are provided below:

a. Convert into the list:

Tuples can be changed into the list by adding the item and then, turning it back to the tuple.


# Original tuple
x = ("apple", "banana", "cherry")

# Convert tuple to list
y = list(x)

# Add "grapes" to the list
y.append("grapes")

# Convert the modified list back to tuple
x_modified = tuple(y)

# Display the modified tuple
print("Original Tuple:")
print(x)
print("\nModified Tuple with 'grapes' added:")
print(x_modified)

Output

Original Tuple:
('apple', 'banana', 'cherry')

Modified Tuple with 'grapes' added:
('apple', 'banana', 'cherry', 'grapes')

b. Add tuple to the tuple

In Python, it is possible to add tuples to tuples. Such as adding an item, creating a new tuple with the item, and then adding it to the existing tuple as shown in the example below.

Example

# Original tuple
x = ("apple", "banana", "cherry")

# Create a new tuple with the value "kiwi"
new_tuple = ("kiwi",)

# Concatenate the original tuple and the new tuple
combined_tuple = x + new_tuple

# Display the combined tuple
print("Combined Tuple:")
print(combined_tuple)

Output

Combined Tuple:
('apple', 'banana', 'cherry', 'kiwi')

What are the examples for converting the list back into the Python Tuple?

It is important to remember that removing items is not possible in Tuples of Python. Let us look into the example below:

# Original tuple
x = ("apple", "banana", "cherry")

# Convert tuple to list
y = list(x)

# Remove "banana" from the list
if "banana" in y:
    y.remove("banana")

# Convert the modified list back to tuple
x_modified = tuple(y)

# Display the modified tuple
print("Original Tuple:")
print(x)
print("\nModified Tuple with 'banana' removed:")
print(x_modified)

Output

Original Tuple:
('apple', 'banana', 'cherry')

Modified Tuple with 'banana' removed:
('apple', 'cherry')

Another way to delete the items in the tuple is to delete it completely with the help of the del keyword:

thistuple = ("apple", "banana", "mango")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Output

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(thistuple)  # this will raise an error because the tuple no longer exists
NameError: name 'thistuple' is not defined

Conclusion

In Python, tuples are like lists but with one crucial difference: they are immutable, meaning once created, their elements cannot be changed. However, there are still ways to update tuples indirectly. Beginners can improve their skills and knowledge on changing or adding the items of tuples in Python. Several examples are illustrated in this article for their reference.

Python – Update Tuples -FAQs

Q1.Can we update the tuple in Python?

Ans. In Python, the value cannot be changed after the tuple is formed.

Q2.Can you mutate a tuple in Python?

Ans.No, it doesn’t have any private attribute to mutate the tuple in Python.

Q3.How do you append to a tuple?

Ans. A tuple can be appended with the help of the += operator.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-update-tuples/feed/ 0
Python List sort() Method https://www.skillvertex.com/blog/python-list-sort-method/ https://www.skillvertex.com/blog/python-list-sort-method/#respond Tue, 19 Mar 2024 06:53:49 +0000 https://www.skillvertex.com/blog/?p=8100 Read more]]>

Table of Contents

The Python list sort () method will help to sort the elements of the list. Hence, it will sort the ascending order by default but will sort the values in the descending values. This article has listed the Python List Sort Method.

What is the Python List sort () Method?

Python list sort method will sort the elements of the list. The list sort() is referred to as the in-build function in Python and will sort the values of the list in ascending or descending order. Whereas, by default, it will then sort the values in ascending order. So, it is referred to as a very useful and simple list operation in Python.

Let us look into the example provided below

Example

# Example list
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Using the sort() method
my_list.sort()

# Displaying the sorted list
print("Sorted List:", my_list)

Output

Sorted List: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

What is the Syntax of the Python List Sort()?

List_name.sort(reverse=True/False, key=myFunc)

How to Use the List Sort () Function

The list sort function in Python will be very easy. Hence, it is required to call the function with the list object. Parameters can be used.

Python list sort() Examples and Use

The use case scenarios of the list sort() method with the examples. Some of the examples are given below:

  1. Sort a List of Numbers in Ascending Order
  2. Sort a List of Alphabets In Ascending Order
  3. Sort a List in Python in Descending Order 
  4. Sort a List in Python By Key

What are Python List sort numbers in Ascending Order?

The sort() method by default will sort elements in ascending order. Check the example given below:

Example

# Sample list of numbers
numbers = [5, 2, 8, 1, 3]

# Sorting the list in ascending order
numbers.sort()

# Displaying the sorted list
print("Sorted Numbers in Ascending Order:", numbers)

Output

Sorted Numbers in Ascending Order: [1, 2, 3, 5, 8]

What is Sort a List of Alphabets in the Ascending Order?

The sort method will sort the list in the order from the A-Z in the alphabet.

Example

# Sample list of alphabets
alphabets = ['c', 'a', 'b', 'f', 'e', 'd']

# Sorting the list in ascending order
alphabets.sort()

# Displaying the sorted list
print("Sorted Alphabets in Ascending Order:", alphabets)

Output

Sorted Alphabets in Ascending Order: ['a', 'b', 'c', 'd', 'e', 'f']

What is Python Sort List in the Descending Order?

In Python, it is possible to sort the list of numbers in descending order and the same will be for alphabets. Thus, to do this, we need to pass the reverse=True and it will sort the numbers or the alphabet in descending order.

Example

# Sample list of numbers
numbers = [5, 2, 8, 1, 3]

# Sorting the list in descending order
numbers.sort(reverse=True)

# Displaying the sorted list
print("Sorted Numbers in Descending Order:", numbers)

Output

Sorted Numbers in Descending Order: [8, 5, 3, 2, 1]

Python sort List by Key 

We will sort the elements with the help of a function and are based on passing the function to the key parameter of the sort() function.

Example

# Sample list of dictionaries
people = [
    {'name': 'John', 'age': 30},
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 35},
]

# Sorting the list of dictionaries by the 'age' key
sorted_people = sorted(people, key=lambda x: x['age'])

# Displaying the sorted list
print("Sorted People by Age:", sorted_people)

Output

Sorted People by Age: [{'name': 'Alice', 'age': 25}, {'name': 'John', 'age': 30}, {'name': 'Bob', 'age': 35}]

Conclusion

In conclusion, the sort() method in Python is a straightforward and convenient way to sort a list in place. It arranges the elements of the list in ascending order by default but can be customized for descending order by providing the reverse=True parameter.

Hence, this method will modify the original list and won’t create a new one. It is a useful tool for quickly organizing numerical or alphabetical data within a list without the need for additional sorting functions.

Python List sort() Method-FAQs

Q1.What does sort () do in Python?

Ans. The sort() method will sort the list in the ascending order.

Q2.How will the Python method sort () sort a list of strings?

Ans. The sorted() function will return the sorted list of the specified iterable object.

Q3.What is the use of the sort () function?

Ans. Sort will return the sorted array of the elements in the array.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-list-sort-method/feed/ 0
Python List Comprehension https://www.skillvertex.com/blog/python-list-comprehension/ https://www.skillvertex.com/blog/python-list-comprehension/#respond Tue, 19 Mar 2024 06:53:34 +0000 https://www.skillvertex.com/blog/?p=8090 Read more]]>

Table of Contents

The Python list comprehension involves a bracket with the expression and will be executed for each element and the for loop to iterate over each element in the Python list. Read this article to learn more about Python List Comprehension.

What is Python List Comprehension?

The List Comprehension will provide the shorter syntax and will make a new list depending on the values of the existing list.

Example

# Example: Squaring numbers from 1 to 5 using list comprehension
squared_numbers = [x**2 for x in range(1, 6)]

# Output
print(squared_numbers)

Output

[1, 4, 9, 16, 25]

What is Python List Comprehension Syntax?

Syntax: newList = [ expression(element) for element in oldList if condition ] 

Parameter
  • Expression: It will represent the operation that you want to execute on every item within the iterable.
  • element: The term ”variable” will indicate each value taken from the iterable.
  • iterable: it will specify the sequence of the elements that are required to iterate through
  • condition: A filter that will help to decide if the element should be added to the new list.

Return: The Return value of the list comprehension will be referred to as the new list that has the modified elements and will satisfy the given criteria.

List Comprehension in Python Example

The example below shows how to list comprehension to find the square of the number in Python.

# Example: List comprehension to square even numbers from a given list
input_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

squared_even_numbers = [x**2 for x in input_numbers if x % 2 == 0]

# Output
print(squared_even_numbers)

Output

[4, 16, 36, 64, 100]

What is the Example of Iteration with List Comprehension

The example provided below illustrates the iteration with the list Comprehension.

# Example: Iterate over a list and add 10 to each element using list comprehension
original_list = [1, 2, 3, 4, 5]

modified_list = [x + 10 for x in original_list]

# Output
print(modified_list)

Output

[11, 12, 13, 14, 15]

What is an example of an Even List Using List Comprehension?

Example

# Example: Create a list of even numbers from 0 to 10 using list comprehension
even_numbers = [x for x in range(11) if x % 2 == 0]

# Output
print(even_numbers)

Output

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

What is Matrix using the List Comprehension?

The example provided below will show the matrix using the list comprehension.

# Example: Create a 3x3 matrix and square each element using list comprehension
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

squared_matrix = [[x**2 for x in row] for row in matrix]

# Output
for row in squared_matrix:
    print(row)

Output

[1, 4, 9]
[16, 25, 36]
[49, 64, 81]

What is the difference between List Comprehension vs For Loop?

There are several ways to iterate through the list. So, the common way is to use the for loop. Check out the example given below.

# Empty list 
List = [] 
  
# Traditional approach of iterating 
for character in 'Skill  vertex!: 
    List.append(character) 
  
# Display list 
print(List) 

Output

['S' , 'k', 'i', 'l', 'l', 'v', 'e', 'r', 't', 'e', 'x','!']

This example above will show the implementation of the traditional approach inorder to iterate through the list such as list, string, tuple, etc. Thus, the list comprehension will perform the same task and will make the program more simple.

Hence, the list comprehension will translate the traditional iteration approach with the help of a for loop and turn it into a simple formula for easy use. So, the approach given below is used to iterate through the list, string, and tuple with the help of list comprehension in Python.

# Using list comprehension to iterate through loop 
List = [character for character in 'Skillvertex!'] 
  
# Displaying list 
print(List) 

Output

['S', 'k', 'i','l', 'l', 'v', 'e', 'r', 't', 'e', 'x',  '!' ]

What is Time Analysis in List Comprehensions and Loops?

The list comprehension in Python will be more efficient both computationally to the coding space and time than the loop. Hence, they will be written in a single line of code. So, the program given below will show the difference between loops and list comprehension depending on the performance.

import time

# Time analysis for List Comprehension
start_time = time.time()

squared_numbers_comprehension = [x**2 for x in range(1, 10**6)]

end_time = time.time()
comprehension_time = end_time - start_time

# Time analysis for Loop
start_time = time.time()

squared_numbers_loop = []
for x in range(1, 10**6):
    squared_numbers_loop.append(x**2)

end_time = time.time()
loop_time = end_time - start_time

# Output time analysis results
print("List Comprehension Time:", comprehension_time, "seconds")
print("Loop Time:", loop_time, "seconds")

Output

List Comprehension Time: 0.09034180641174316 seconds
Loop Time: 0.1588280200958252 seconds

What is Nested List Comprehension?

The Nested List Comprehension is referred to as the list comprehension within the other list comprehension and works similarly to the nested for loops. The program given below shows the nested loop.

# Example: Nested list comprehension to create a 3x3 matrix with squared elements
matrix_size = 3
squared_matrix = [[x**2 for x in range(row * matrix_size + 1, (row + 1) * matrix_size + 1)] for row in range(matrix_size)]

# Output
for row in squared_matrix:
    print(row)

Output

[1, 4, 9]
[16, 25, 36]
[49, 64, 81]

What is List Comprehensions and Lambda

Lambda Expressions are referred to as the shorthand representations of the Python functions. With the help of list comprehensions with lambda, it will make an efficient combination.

# Example: List comprehension with lambda function to square each element
original_list = [1, 2, 3, 4, 5]

squared_list = [(lambda x: x**2)(x) for x in original_list]

# Output
print(squared_list)

Output

[1, 4, 9, 16, 25]

Conditionals in the List Comprehension

This will add the conditions statements to the list comprehension. So, it will make a list using the range, operators, etc, and will apply some conditions to the list with the help of if statements.

What is the Example of Python List Comprehension using the if-else

Check out the example to learn more about Python List Comprehension using the if-else.

Example

# Example: List comprehension with if-else to square even and cube odd numbers
original_list = [1, 2, 3, 4, 5]

modified_list = [x**2 if x % 2 == 0 else x**3 for x in original_list]

# Output
print(modified_list)

Output

[1, 4, 27, 16, 125]

What is the Example of Nested IF with the List Comprehension?

Example

# Example: Nested if in list comprehension to filter even numbers greater than 2
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

filtered_list = [x for x in original_list if x > 2 if x % 2 == 0]

# Output
print(filtered_list)

Output

[4, 6, 8]

Display the square of numbers from 1 to 10

Check out the example below to display the square of numbers from 1 to 10.

Example

# Using a for loop to display the square of numbers from 1 to 10
for num in range(1, 11):
    square = num ** 2
    print(f"The square of {num} is: {square}")

Output

The square of 1 is: 1
The square of 2 is: 4
The square of 3 is: 9
The square of 4 is: 16
The square of 5 is: 25
The square of 6 is: 36
The square of 7 is: 49
The square of 8 is: 64
The square of 9 is: 81
The square of 10 is: 100

What is the Example to Display Transpose of 2D- Matrix?

Example

# Function to calculate the transpose of a matrix
def transpose(matrix):
    # Using zip() to transpose the matrix
    transposed_matrix = [list(row) for row in zip(*matrix)]
    return transposed_matrix

# Example 2D matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Display original matrix
print("Original Matrix:")
for row in matrix:
    print(row)

# Display transpose of the matrix
transposed_matrix = transpose(matrix)
print("\nTransposed Matrix:")
for row in transposed_matrix:
    print(row)

Output

Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Transposed Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

Toggle the case of each character in the string

Example

# Function to toggle the case of each character in a string
def toggle_case(input_string):
    toggled_string = ''.join([char.lower() if char.isupper() else char.upper() for char in input_string])
    return toggled_string

# Example string
input_string = "Hello World!"

# Display original string
print("Original String:", input_string)

# Toggle the case of each character
toggled_string = toggle_case(input_string)

# Display the result
print("Toggled String:", toggled_string)

Output

Original String: Hello World!
Toggled String: hELLO wORLD!

What is the example to reverse each string in a Tuple?

# Function to reverse each string in a tuple
def reverse_strings_in_tuple(input_tuple):
    reversed_tuple = tuple(s[::-1] for s in input_tuple)
    return reversed_tuple

# Example tuple of strings
original_tuple = ("hello", "world", "python", "code")

# Display original tuple
print("Original Tuple:", original_tuple)

# Reverse each string in the tuple
reversed_tuple = reverse_strings_in_tuple(original_tuple)

# Display the result
print("Reversed Tuple:", reversed_tuple)

Output

Original Tuple: ('hello', 'world', 'python', 'code')
Reversed Tuple: ('olleh', 'dlrow', 'nohtyp', 'edoc')

What is the Example of creating the list of Tuples from the two separate Lists?

Let us look into the example given below to create the two lists of names and ages with the help of zip() in the list comprehension so, it is possible to insert the name and age as the tuple to the list.

Example

# Function to create a list of tuples from two separate lists
def create_tuples(list1, list2):
    tuple_list = list(zip(list1, list2))
    return tuple_list

# Example lists
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']

# Display original lists
print("List 1:", list1)
print("List 2:", list2)

# Create a list of tuples from the two lists
tuple_list = create_tuples(list1, list2)

# Display the result
print("List of Tuples:", tuple_list)

Output

List 1: [1, 2, 3, 4]
List 2: ['a', 'b', 'c', 'd']
List of Tuples: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

What is the Example to display the sum of digits of all the odd elements in the list?

The example provided below has made a list and that will help us to find the digit sum of every odd element in the list.

Example

# Function to calculate the sum of digits in a number
def sum_of_digits(number):
    return sum(int(digit) for digit in str(abs(number)))

# Function to calculate the sum of digits for odd elements in the list
def sum_of_digits_for_odd_elements(input_list):
    odd_elements = [element for element in input_list if element % 2 != 0]
    sum_of_digits_odd = sum(sum_of_digits(element) for element in odd_elements)
    return sum_of_digits_odd

# Example list of numbers
number_list = [123, 45, 678, 91, 234]

# Display original list
print("Original List:", number_list)

# Calculate the sum of digits for odd elements in the list
result = sum_of_digits_for_odd_elements(number_list)

# Display the result
print("Sum of digits for odd elements:", result)

Output

Original List: [123, 45, 678, 91, 234]
Sum of digits for odd elements: 21

Conclusion

In conclusion, Python List Comprehension is a concise and powerful feature that allows for the creation of lists in a more compact and readable manner. It provides a succinct syntax to generate lists, filter elements, and apply expressions in a single line of code. List comprehensions enhance code readability, reduce the need for explicit loops, and contribute to more expressive and Pythonic programming.

Moreover, they are particularly useful for tasks involving iteration, filtering, and transformation of data, making code both efficient and elegant. Overall, Python List Comprehension is a valuable tool for simplifying list-related operations and improving code efficiency.

Python List Comprehension- FAQs

Q1.What is list comprehension in Python?

Ans. The list comprehension is very easy to read, compact, and has an elegant way of forming the list from the existing iterable object.

Q2.What are the 4 types of comprehension in Python?

Ans. List comprehension, dictionary comprehension, set comprehension, and generator comprehension are the 4 types of comprehension in Python.

Q3. What is list comprehension in Python in range?

Ans. It is a concise syntax that is used to create the list from the range or an iterable object by applying the specified object on each of its items.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-list-comprehension/feed/ 0
Python Functions https://www.skillvertex.com/blog/python-functions/ https://www.skillvertex.com/blog/python-functions/#respond Tue, 19 Mar 2024 06:47:28 +0000 https://www.skillvertex.com/blog/?p=7272 Read more]]>

Table of Contents

A function is considered a block that will run a particular task. Let’s look into the article to learn more about Python Functions.

What are Python Functions?

Python Functions are the blocks of statements that will return the specific task. The main goal is to put some repeatedly done tasks together and thus, create a function. This will allow us to write the code repeatedly for several inputs. Hence, we do this function calls to reuse code in it repeatedly.

What is the Syntax of Python Function Declaration?

The syntax of the Python Function declaration is given below:

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]

What are the types of Functions in Python?

1. Built-in Library Function- This is known as the standard function in Python which is available to utilize.

2. User-defined Function- Through this, it is possible to make our functions depending on the requirements.

Creating a Function in Python

Python function can be defined using the def keyword. According to the requirements, you can add any types of functionalities and properties to it.

Look at the example given below:

# A simple Python function 
 
def fun():
  print("Welcome to SV")

Calling a Python Function

Thus, after creating the function. It can be named with the name of the function and is followed by the parenthesis that has parameters of the specific function.

# Define a function
def greet(name):
    return f"Hello, {name}!"

# Call the function
result = greet("John")

# Print the result
print(result)

Output

Hello, John!

Python Function with Parameters

In Python, the return type of the function and data type of arguments is possible. This function is possible in Python and in several versions of Python including Python 3.5 and above.

Defining and Calling a function with Parameters

The syntax is provided below:

 def function_name(parameter: data_type) -> return_type:
    """Docstring"""
    # body of the function
    return expression

Example

# Define a function with parameters
def add_numbers(a, b):
    result = a + b
    return result

# Call the function with arguments
sum_result = add_numbers(5, 7)

# Print the result
print("Sum:", sum_result)

Output

Sum: 12

What is Python Function Arguments

Arguments are referred to as the value that will be passed inside the parenthesis of the function. The function consists of the number of arguments that are separated by a comma.

Look into the example given below:

# Function to check if a number is even or odd
def even_or_odd(number):
    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

# Function with default argument (exponent) using even or odd numbers
def power(base, exponent=2):
    return base ** exponent

# Calling functions with even and odd numbers
number_to_check = 7
result_even_odd = even_or_odd(number_to_check)
power_result = power(number_to_check, exponent=3)  # Using odd number with a different exponent

# Printing the results
print(f"{number_to_check} is {result_even_odd}")
print(f"Power of {number_to_check} to the 3rd exponent:", power_result)

Output

7 is Odd
Power of 7 to the 3rd exponent: 343

What are the types of Python Function Arguments?

It is known that Python will allow several types of arguments that will be passed at the time of a function call. In Python, there are 4 types of function calls.

a. Default argument

b.Keyword argument

c. Positional argument

d. Arbitrary argument

What is a Default Argument?

The default argument is referred to as a parameter that will predict a default value when the value is not assigned in the function call for the argument.

# Function with default argument
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# Calling the function with and without providing the default argument
result1 = greet("Alice")          # Uses the default greeting
result2 = greet("Bob", "Hi")      # Provides a custom greeting

# Printing the results
print(result1)
print(result2)

Output

Hello, Alice!
Hi, Bob!

What is Keyword Argument?

In Python, the keyword Argument will allow the caller to mention the argument name along with the values, in which it is not required to remember the order of parameters.

# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
    print(firstname, lastname)
 
 
# Keyword arguments
student(firstname='Skill', lastname='Vertex')
student(lastname='Vertex', firstname='Skill')

What are Positional Arguments?

The Position Arguments is used during the function call as the first argument will be given a name, and the second argument will be provided to age.

Example

# Function with positional arguments
def add_numbers(a, b):
    result = a + b
    return result

# Calling the function with positional arguments
sum_result = add_numbers(5, 7)

# Printing the result
print("Sum:", sum_result)

Output

Sum: 12

What is Docstring?

The first string after the function is referred to as the document string. The main goal of this Docstring is to define the functionality of the function.

The syntax of Docstring is given below:

Syntax: print(function_name.__doc__)

Example

def greet(name):
    """
    This function takes a name as a parameter and returns a greeting message.

    Parameters:
    - name (str): The name of the person to greet.

    Returns:
    str: A greeting message.
    """
    return f"Hello, {name}!"

# Accessing the docstring
print(greet.__doc__)

# Calling the function
result = greet("Alice")

# Printing the result
print(result)

Output

This function takes a name as a parameter and returns a greeting message.

Parameters:
- name (str): The name of the person to greet.

Returns:
str: A greeting message.

Hello, Alice!

What are Recursive Functions in Python?

Recursive in Python will be used when a function calls by itself. Hence, it states that it is required to create the recursive function to solve the Mathematical and Recursive Problems.

def factorial(n):
    """
    Recursive function to calculate the factorial of a number.

    Parameters:
    - n (int): The number for which to calculate the factorial.

    Returns:
    int: The factorial of the input number.
    """
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Calling the recursive function
result = factorial(5)

# Printing the result
print("Factorial:", result)

Output

Factorial: 120

Note: Use the Recursive function with a warning, as it will turn into a/ non-terminating loop.

What is a Return Statement in Python Function?

The return statement functions to exit from the function and return back to the function caller . Thus it will get a specified value

The syntax is provided below

return [expression_list]

Example

def add_numbers(a, b):
    """
    This function takes two numbers as parameters and returns their sum.

    Parameters:
    - a (int): The first number.
    - b (int): The second number.

    Returns:
    int: The sum of the two numbers.
    """
    result = a + b
    return result

# Calling the function and storing the result
sum_result = add_numbers(3, 7)

# Printing the result
print("Sum:", sum_result)

Output

Sum: 10

What is Pass by Reference and Pass by Value?

In Python, every variable name has a reference. In which, when the variable is passed, then the new reference of the object is made. Parameter passing in Python is considered similar to that of reference passing in Java.

# Pass by assignment example

# Function modifying a mutable object (list)
def modify_list(my_list):
    my_list.append(4)
    my_list[0] = 99

# Function modifying an immutable object (integer)
def modify_integer(my_integer):
    my_integer = 10

# Original list and integer
original_list = [1, 2, 3]
original_integer = 5

# Call functions with the original objects
modify_list(original_list)
modify_integer(original_integer)

# Print the original objects after function calls
print("Modified List:", original_list)      # [1, 2, 3, 4, 99]
print("Modified Integer:", original_integer) # 5

Output

Modified List: [1, 2, 3, 4, 99]
Modified Integer: 5

Conclusion

In summary, Python functions are versatile tools that help organize code into reusable and manageable blocks. They allow developers to define specific tasks or operations that can be executed with different inputs. With parameters, default values, and return statements, functions provide flexibility in handling various scenarios.

Additionally, docstrings serve as valuable documentation to understand a function’s purpose and usage.

Python Functions- FAQs

Q1.What is a Python function?

Ans. It is referred to as a block of statements that does a particular task.

Q2. How to define a function?

Ans. The relation between a set of inputs having one output each will define the function.

Q3. What is a def in Python example?

Ans. def is referred to as a block keyword that is followed by the function name and the block name.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-functions/feed/ 0
Python-Add List Items https://www.skillvertex.com/blog/python-add-list-items/ https://www.skillvertex.com/blog/python-add-list-items/#respond Fri, 08 Mar 2024 07:39:22 +0000 https://www.skillvertex.com/blog/?p=8058 Read more]]>

Table of Contents

In Python, you can use different methods to add elements to the list. So, the 3 cases of adding an element to the list are mentioned in this. Read this article to learn more about Python-Add List Items.

How to Add Items to a List in Python?

The data structures can be manipulated in the data structures and that needs adding elements to the lists. Several methods are used with those specific use cases. The methods used to add elements are given below:

a.insert() method

b.append() method

c.concatenation() method

d. extend() method

e.list unpacking method

f. Slice and concatenation method

How to Insert Element to the List Using the Insert() Method

The insert() method will help you to add the elements to the list at the index. So, the insert () method will enable us to insert elements at the specific index.

Example

# Initializing a list
my_list = [1, 2, 3, 5, 6]

# Displaying the original list
print("Original List:", my_list)

# Inserting elements at specific positions
my_list.insert(2, 4)  # Insert 4 at index 2
my_list.insert(5, 7)  # Insert 7 at index 5

# Displaying the modified list
print("List after insertion:", my_list)

Output

Original List: [1, 2, 3, 5, 6]
List after insertion: [1, 2, 4, 3, 5, 7, 6]

In the example provided above, the insert method allows us to insert elements 4 and 7 at the specific positions in the list.

How to Add Elements to a List using the append() Method?

The append () method will allow us to add elements to the end of the list. append() method will add the item to the list at the last index. This will help us to pass the multiple values to the list.

Example

# Initializing a list
my_list = [1, 2, 3, 5, 6]

# Displaying the original list
print("Original List:", my_list)

# Inserting elements at specific positions
my_list.insert(2, 4)  # Insert 4 at index 2
my_list.insert(5, 7)  # Insert 7 at index 5

# Displaying the modified list
print("List after insertion:", my_list)

Output

Original List: [1, 2, 3, 5, 6]
List after insertion: [1, 2, 4, 3, 5, 7, 6]

How to Add Element to the List Using the Concatenation?

It will allow you to create the list and have the element that you need to add. So, it will concatenate with the existing list. Moreover, it is possible to concatenate the two lists using the + operator to add the list to the list in Python.

Example

# Initializing a list
my_list = [1, 2, 3, 5, 6]

# Displaying the original list
print("Original List:", my_list)

# Adding a new element to the list using concatenation
new_element = 4
my_list = my_list + [new_element]

# Displaying the modified list
print("List after adding a new element:", my_list)

Output

Original List: [1, 2, 3, 5, 6]
List after adding a new element: [1, 2, 3, 5, 6, 4]

How do you add an Element using the extend() Method?

The extend method will help you to add the element from another list to the end of the list.

Example

# Initializing a list
my_list = [1, 2, 3, 5, 6]

# Displaying the original list
print("Original List:", my_list)

# Adding elements to the list using extend method
new_elements = [4, 7]
my_list.extend(new_elements)

# Displaying the modified list
print("List after adding new elements using extend:", my_list)

Output

Original List: [1, 2, 3, 5, 6]
List after adding new elements using extend: [1, 2, 3, 5, 6, 4, 7]

How to add an element to the List using List Unpacking?

It is possible to use the unpacking to add the elements from the other list to the end of the list.

Example 1: add the elements at the end of the list

# Initializing a list
my_list = [1, 2, 3, 5, 6]

# Displaying the original list
print("Original List:", my_list)

# Adding elements to the list using list unpacking
new_element = 4
my_list = [*my_list, new_element]

# Displaying the modified list
print("List after adding a new element using list unpacking:", my_list)

Output

Original List: [1, 2, 3, 5, 6]
List after adding a new element using list unpacking: [1, 2, 3, 5, 6, 4]

Example 2: Add elements at the specific index in the list

# Initializing a list
my_list = [1, 2, 3, 5, 6]

# Displaying the original list
print("Original List:", my_list)

# Adding elements at specific indices
index_to_add = 2
elements_to_add = [4, 7]

# Using slicing to insert elements at the specified index
my_list = my_list[:index_to_add] + elements_to_add + my_list[index_to_add:]

# Displaying the modified list
print("List after adding elements at index", index_to_add, ":", my_list)

Output

Original List: [1, 2, 3, 5, 6]
List after adding elements at index 2 : [1, 2, 4, 7, 3, 5, 6]

How to Add Element to a List Using Slicing and Concatenation

In Python, slice the list into two parts and then concatenate the new element and the second part of the original list.

Example

# Original list
original_list = [1, 2, 3, 4, 5]

# Element to be added
new_element = 6

# Index at which the element should be added
index_to_add = 2

# Using slicing and concatenation to add the element
modified_list = original_list[:index_to_add] + [new_element] + original_list[index_to_add:]

# Displaying the original and modified lists
print("Original List:", original_list)
print("Modified List:", modified_list)

Output

Original List: [1, 2, 3, 4, 5]
Modified List: [1, 2, 6, 3, 4, 5]

Conclusion

Adding items to a list in Python is a fundamental operation, and the process can be made accessible through the concept of slicing and concatenation.

By combining these parts using the + operator, a new list (modified_list) is created with the desired element seamlessly integrated at the specified position. This technique, likened to cutting, inserting, and sticking parts together, provides a dynamic way to modify lists in Python programs.

Python-Add List Items- FAQs

Q1. Can you add items in a list Python?

Ans. It is possible to use the append() to add any object in the given list.

Q2.How do you add things together in a list Python?

Ans. The easiest way to sum the elements in the Python list is through the inbuilt sum() function with the syntax and the sum(list of numbers).

Q3. Can we add two lists in Python?

Ans. It is possible to add two or more lists with the help of the + operator.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-add-list-items/feed/ 0