Python List – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Thu, 27 Apr 2023 16:29:18 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python List – Java2Blog https://java2blog.com 32 32 Get Every Other Element in List in Python https://java2blog.com/get-every-other-element-list-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-every-other-element-list-python https://java2blog.com/get-every-other-element-list-python/#respond Tue, 04 Oct 2022 17:37:55 +0000 https://java2blog.com/?p=20882 A list is one of the more versatile data types among the others provided in Python. As we know lists can store multiple items in one single variable, there is often a need to get only a handful of items from a given list.

Get Every Other Element in List in Python

This tutorial focuses on and demonstrates the different ways available to get every other element in a list in python.

There are numerous ways to tackle this problem, ranging from simple list slicing to a lambda function, all of which have been thoroughly explained in this article below.

Using List Slicing

List slicing is a common practice and is utilized to access the elements of a list in a specified range.
List slicing is able to return a new, more specific list from the original list by taking in the start, end, and step values specified by the user. All three are separated by a colon [:] sign.

The parameters mentioned above have the following explanations:

  • start: The beginning point of the range that the user defines.
  • end: The end point of the range that the user defines.
  • step: the step count that the user can define.

The following code uses list slicing to get every other element in a list in Python.

x = [10,20,30,40,50,60,70,80,90,100]
y = x[::2]
print(y)

Output:

[10,30,50,70,90]

Using the list.append() function along with the range() function

The list.append() method, as the name suggests, is utilized to append items in a given list.
The range() function is used to specify a range that the function is to be applied upon. This function has three parameters, which are start, stop, and step. All of these three are separated by a comma [,] sign.

  • start: It marks the beginning of the range.
  • stop: It marks the end of the range.
  • step: It marks the step value that is to be taken.

The following code uses the list.append() function along with the range() function to get every other element in a list in Python.

x = [10,20,30,40,50,60,70,80,90,100]
def ese(a):
       y = [ ]
       for i in range(1,len(a),2):
           y.append(a[i])
       return y
print(ese(x))

Output:

[20,40,60,80,100]

Here is article on how to increment for loop by 2 in Python.

Using list comprehension and the range() function with conditionals

List comprehension is capable of creating a list with reference to an already existing list. It also reduces the chunk of code and makes the code more compact.
Here, we utilize the range() function with conditionals rather than the convention start, stop, and step parameters.

The following code uses list comprehension and the range() function with conditionals to get every other element in a list in Python.

x = [10,20,30,40,50,60,70,80,90,100]
print([x[i] for i in range(len(x)) if i % 2 == 0])

Output:

[10,30,50,70,90]

Using list comprehension and the range() function with step

List comprehension, as we know, helps us avoid the generic for loop and makes it possible to finish the code in a single line.
Here, we utilize the range() function with the conventional start, stop, and step to implement the task at hand.

The following code uses list comprehension and the range() function with step to get every other element in a list in Python.

x = [10,20,30,40,50,60,70,80,90,100]
print([x[i] for i in range(0,len(x),2)])

Output:

[10,30,50,70,90]

Using the enumerate() function along with list comprehension

The enumerate() function is a handy addition to a user’s Python code as this purpose serves the function of assisting the user by adding a counter to any given iterable and returning it as an enumerating object.

List comprehension, when used along with the enumerate() function, is capable of implementing the task of getting every other element in a list in Python.

The following code uses the enumerate() function along with list comprehension to get every other element in a list in Python.

x = [10,20,30,40,50,60,70,80,90,100]
print ([a for i, a in enumerate(x) if i % 2 == 0])

Output:

[10, 30, 50, 70, 90]

Using a lambda function

A lambda function is an anonymous function that is capable of holding a single expression while taking in n number of arguments.

The lambda function can implement the task of getting every other element in a list in Python when utilized with the range() function and specifying conditional.

This approach also makes use of an additional filter() function that is utilized to place the elements of a given sequence under a conditional and tests whether they are true or not. On the basis of this, it filters the specified sequence.

The following code uses the lambda function to get every other element in a list in Python.

x = [10,20,30,40,50,60,70,80,90,100]
y = [x[i] for i in filter(lambda a: a % 2 == 1, range(len(x)))]
print(y)

Output:

[20, 40, 60, 80, 100]

Conclusion.

This tutorial discusses several methods that successfully carry out the task of getting every other element in a list in Python. Some methods can be quite complex for beginners to understand but all of the methods provide accurate answers. The programmer can choose one out of the lot depending on the results they are seeking.

]]>
https://java2blog.com/get-every-other-element-list-python/feed/ 0
Convert String List to Integer List in Python https://java2blog.com/convert-string-list-to-integer-list-python/?utm_source=rss&utm_medium=rss&utm_campaign=convert-string-list-to-integer-list-python https://java2blog.com/convert-string-list-to-integer-list-python/#respond Thu, 27 Apr 2023 16:29:18 +0000 https://java2blog.com/?p=23524 Using map() Method

Use the map() method with list() method to convert string list to integer list in Python.

string_list = ['5', '6', '7', '8', '9']
integer_list = list(map(int, string_list))
print(integer_list)
for item in integer_list:
    print(type(item))
[5, 6, 7, 8, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

First, we defined a variable named string_list and set its value to a list having five string values. Next, we used the map() method, which applied the int() method to every element in string_list to change its type from str (string) to int (integer). Once the map() method applied int() to all elements in string_list, it returned a map object which we passed to the list() method to convert it into a list and stored in the integer_list variable.

Finally, we used the print() method and passed integer_list as a parameter to print it on the console. We also used a for loop to iterate over the integer_list to check each element’s data type in the integer_list using the type() function. We also printed the data type of each element on the console using the print() method.

In the above example, the map() method applied the int() method, which was specified as a parameter. Note that we do not write parentheses (()) while writing functions as a parameter in the map() method. If you don’t want to use this approach because you are uncomfortable writing functions without (), then the following solution is for you.

string_list = ['5', '6', '7', '8', '9']
integer_list = list(map(lambda i: int(i), string_list))
print(integer_list)
for item in integer_list:
    print(type(item))
[5, 6, 7, 8, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

This example is similar to the previous one, but we used the lambda expression (also called the lambda function) this time; it is a small anonymous function which can accept any number of arguments but have one expression only. In the above example, the map() method applied the lambda i: int(i) function to every element in the string_list to convert it from string to integer.

Unlike the previous example, once map() applies the specified function to all elements in string_list, it returns a map object that we passed to the list() method to convert into a list and store it in integer_list variable. Finally, we printed the entire list and data type of each element in integer_list.

In Python 2, using the list() method to convert a map object to a list is not required because you would already have it, but you will not get any error if you use the list() method.

Using for Loop

Use the for loop to convert string list into integer list in Python.

string_list = ['5', '6', '7', '8', '9']
integer_list = []
for item in string_list:
    integer_list.append(int(item))
print(integer_list)
for item in integer_list: print(type(item))
[5, 6, 7, 8, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

Again, we initialized a list with five string values representing integers and stored it in the string_list variable. After that, we also defined integer_list and set it to an empty list. Next, we used a for loop to iterate over each item in the string_list. In each iteration, we used the int() method to convert the current item from string to integer and passed it as an argument to the append() method to populate the integer_list.

Finally, we used the print() method to display the entire integer_list and another for loop to show each element’s data type in integer_list.

Using List Comprehension

Use list comprehension to convert string list to integer list in Python.

string_list = ['5', '6', '7', '8', '9']
integer_list = [int(item) for item in string_list]
print(integer_list)
for item in integer_list: print(type(item))
[5, 6, 7, 8, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

Here, we used list comprehension to convert strings to integers. Learners find list comprehension challenging but let’s make it easy to understand. The [int(item) for item in string_list] is the list comprehension that creates a list of integers by looping over every element, an item in the string_list.

For every item in string_list, the int(item) was applied to convert item from string to an integer value; this resulting integer value was added to a new list created by list comprehension. Once all elements in string_list have been looped over and converted to integers, a new list of integers was returned by list comprehension, which we stored in the integer_list variable for further use.

Lastly, we used print() to show the entire integer_list and for loop to display each item’s data type in integer_list.

If you have a question at this point and wonder if the map() and lambda functions are doing the same thing, then why have list comprehensions? Because it is a more readable and concise way to do the same thing as lambda and map() functions, particularly useful when we need to do additional operations on every item of the list.

Now, think of a situation where string_list will have string values representing a mixture of integer and float values. How will you convert them to integer values? See the following solution to learn it.

string_list = ['5', '6.0', '7', '8.8', '9']
integer_list = [round(float(item)) for item in string_list]
print(integer_list)
for item in integer_list: print(type(item))
[5, 6, 7, 9, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

This code is similar to the previous example, but for this solution, we used the float() method to convert each item to a floating-point number and passed it to the round() method to convert it to the nearest integer number.

Remember, if you have an actual string value (a text value) in your string_list and use any of the solutions demonstrated yet in this article, you will end up with a ValueError. For example, you will get ValueError if you set a string list as string_list = ['5', '6', 'text']. Note that having an actual integer value ( such as string_list = ['5', '6', 7]) in your string_list will not produce any error.

Using eval() and ast.literal_eval() Methods

Use the eval() method with a list comprehension to convert string list to integer list in Python.

string_list = ['5', '6', '7', '8', '9']
integer_list = [eval(item) for item in string_list]
print(integer_list)
for item in integer_list: print(type(item))
[5, 6, 7, 8, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

In the above example, we used the eval() method, which took an item as a parameter; note that the item is a string representation of an integer value such as '5'. The eval() returned its corresponding integer value because it evaluates the given expression and executes it if it is a legal Python statement.

Note that we will get NameError if string_list will have any actual string value such as ['5', 'text', '7', '8', '9'] and will get TypeError if string_list will have any actual integer value such as ['5', 6, '7'].

Use the literal_eval() method of the ast module to convert string list to integer list in Python.

import ast
string_list = ['5', '6', '7', '9']
integer_list = [ast.literal_eval(item) for item in string_list]
print(integer_list)
for item in integer_list: print(type(item))
[5, 6, 7, 9]
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

This code snippet is similar to the previous one, but we used the ast.literal_eval() method to convert all list items from string to integer. Note that we will get ValueError if an actual integer or float value is found in the string_list such as ['5', 6, 6.7].

You might think that if both ast.literal_eval() and eval() functions evaluate the expressions, then why use them separately? Because they have some differences, which make one desirable over the other based on the use case.

The eval() is Python’s built-in function to evaluate the specified string as Python expressions. It is used to evaluate any valid Python expression, such as statements, and can execute any arbitrary code; however, using eval() can be harmful if used with untrusted inputs as it can run malicious code and result in security threats.

On the other side, the ast.literal_eval() is safer than eval(), which evaluates the specified string as a Python expression and returns an object only if it is a literal value (number, tuple, string, list, boolean, dictionary, or None). It does not evaluate statements or arbitrary code, which makes it a safer option while working with untrusted inputs. Evaluating literal values only makes the ast.literal_eval() function less flexible than eval().

Considering performance, the eval() is faster than the ast.literal_eval() because it does not have to check whether the specified expression being evaluated is a literal value.

Now, the point is when to use which method? If you are sure that input is safe and you must evaluate a string as a Python expression, then you can proceed with the eval() method. However, if you are not confident about the input, whether it is safe or not, and you only have to evaluate a literal value, then use ast.literal_eval().

Until this point, we have learned various solutions to convert string list to integer list, but none of them works on different variants of string_list, such as ['5', 6, '7'], ['5', 6, '7', 8.8], and `[‘5’, ‘6’, ‘text’]. So let’s define a function in the following section which can handle all these.

Using User-defined Function

To convert a string list to an integer list in Python:

  • Use the def keyword to define a function.
  • Inside this function, defined in the first step:
    • Use the if statement with the not operator to check if the item is empty.
    • If the item is not empty, use float() to convert it to float; otherwise, raise ValueError.
    • If the item is converted to float, use int() to check if it can be represented as an integer.
    • If the float and integer values are the same, return the integer value; otherwise, float value.
    • If the item can’t be converted to float, return it as it is.
  • Use the map() method to apply the function (defined in the first step) to every item in the string list.
  • Use list() method to convert map object (returned by map()) to list.
  • Use the print() method to display the converted list.
def convert_string_list_to_integer_list(list_item):
    if not list_item:
        return list_item
    try:
        float_number = float(list_item)
        integer_number = int(float_number)
        return integer_number if float_number == integer_number else float_number
    except ValueError:
        return list_item

string_list = ['some', '4', '9.8', 1, 8.8, 'text']
integer_list = list(map(convert_string_list_to_integer_list, string_list))
print(integer_list)
['some', 4, 9.8, 1, 8.8, 'text']

If you also want to round the floating-point numbers to the nearest integers, you can use the round() method:

def convert_string_list_to_integer_list(list_item):
    if not list_item:
        return list_item
    try:
        float_number = round(float(list_item))
        integer_number = int(float_number)
        return integer_number if float_number == integer_number else float_number
    except ValueError:
        return list_item

string_list = ['some', '4', '9.8', 1, 8.8, 'text']
integer_list = list(map(convert_string_list_to_integer_list, string_list))
print(integer_list)
['some', 4, 10, 1, 9, 'text']

That’s all about convert String List to Integer List in Python.

]]>
https://java2blog.com/convert-string-list-to-integer-list-python/feed/ 0
Convert List to Integer in Python https://java2blog.com/convert-list-to-integer-python/?utm_source=rss&utm_medium=rss&utm_campaign=convert-list-to-integer-python https://java2blog.com/convert-list-to-integer-python/#respond Tue, 28 Feb 2023 08:05:06 +0000 https://java2blog.com/?p=23022 Using for Loop

To convert the entire list into one integer in Python:

  • Create a list having integer-type elements.
  • Declare and initialize a variable with 0; it will be used to hold the final integer value.
  • Use the for loop to iterate over the list items.
  • In each iteration:
    • multiply the variable created in the second step with 10 and add the current list item.
    • Assign the value (produced in the previous step) to the variable created in step two.
my_list = [5, 6, 7]
number = 0
for current_digit in my_list:
    number = number*10 + current_digit
print(number)
567

First, we created a list named my_list with three elements of integer type. Then, our job is to convert that from a list of integers to one integer value; for that, we defined and initialized the variable named number with 0. Then, we used the for loop to go through all the list items.

For every current_digit in the my_list, we multiplied the number with 10 and added current_digit. This will have the effect of shifting digits of the number variable to the left by one place and adding the upcoming digit to the right. For instance, we have a [5, 6, 7] list in the above example, which will have the following iterations:

  1. number = 0*10+5 = 5
  2. number = 5*10+6 = 56
  3. number = 56*10+7 = 567

Once the loop is over, we will have 567 as one integer type value; to check its type, you can use the type() method as type(number).

Using List Comprehension

To convert the entire list into one integer in Python:

  • Create a list having integer-type elements.
  • Use list comprehension to convert each list item from integer type value to string type value; for instance, from [5, 6, 7] to ['5', '6', '7'].
  • Use the join() method to join all the list items to make a single string value, such as from ['5', '6', '7'] to '567'.
  • Use the int() method for changing data type from string to integer.
my_list = [5, 6, 7]
new_list = [str(current_integer) for current_integer in my_list]
string_value = "".join(new_list)
number = int(string_value)
print(number)
567

After creating a list named my_list having integer type elements, we used list comprehension to loop over all the list items and converted every item to a string by wrapping around with the str() method. The str() method converts the specified value to a string type value. At this point, we had my_list as ['5', '6', '7'], which we stored in the new_list variable.

Next, we used the join() method to join all the elements of new_list to make it one string value and stored it in the string_value variable. Using the join() method, we transformed ['5', '6', '7'] to '567'.

Now, we can use the int() method to dynamically cast string_value to an integer value which we saved in number. Finally, we used the print() method to print the value of the number variable; we can also print the type of number by printing as print(type(number)).

Using map() and join() Methods

To convert the entire list into one integer in Python:

  • Create a list having integer-type elements.
  • Use the map() method to convert every list item’s type from integer to string.
  • Use the join() method to join all the list items to make it one string-type value.
  • Use the int() method to cast the type from string to integer dynamically.
my_list = [5, 6, 7]
new_list = map(str, my_list)
string_value = ''.join(new_list)
number = int(string_value)
print(number)
567

This code fence is similar to the previous example, but we used functions instead of list comprehension. Here, we used the map() method to transform [5, 6, 7] to ['5', '6', '7'] and saved it in new_list variable. If you are curious how the map() function works, then let’s understand that below.

We passed two arguments to map(); the first was the function (str), and the second was the iterable (my_list). The map() method iterated over the my_list items where every list item was passed to the str function as an argument; for instance, the first list item 5 was sent to the str function as str(5), which returned string type value as '5'. By using the map() method, we transformed the [5, 6, 7] to ['5', '6', '7'], which we saved in the new_list variable.

This new_list variable was then passed to the join() method to join all the list items and form one string type value as '567' that we stored in string_value. Finally, we performed typecasting using the int() method. This int() method took string_value as a parameter and converted its type from string to integer that we saved in the number variable.

Using the reduce() Method with lambda Expression

To convert the entire list into one integer in Python:

  • Create a list having integer-type elements.
  • Use the reduce() method with the lambda function to convert the entire list to one integer.
from functools import reduce
my_list = [5, 6, 7]
number = reduce(lambda x, y: x*10 + y, my_list)
print(number)
567

This code example is the first example’s more concise and professional form. Here, we did the same, multiplied the number by 10, added the current digit, and used this result for the next integer. But this time, number is x and current_digit is y, and we used the reduce() function with the lambda function to achieve this.

The reduce() method took two arguments: first was the function (lambda), and second was the iterable (my_list). The lambda expression took two arguments, x & y, and produced x*10+y. The reduce() method’s job was to apply the lambda function to the first two list items of my_list, then apply the same function to the outcome and next item, and so on, till all items have been processed.

Once the reduce() method is done with its processing, we will get the answer which would be an integer-type value.

That’s all about how to convert List to Integer in Python.

]]>
https://java2blog.com/convert-list-to-integer-python/feed/ 0
Get First n Elements of List in Python https://java2blog.com/get-first-n-elements-of-list-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-first-n-elements-of-list-python https://java2blog.com/get-first-n-elements-of-list-python/#respond Mon, 20 Feb 2023 07:24:52 +0000 https://java2blog.com/?p=23028 Using List slicing

Use list slicing to get first n elements of List in Python. Here’s an example:

my_list = [10, 20, 30, 40, 50, 60]
n = 4
first_n_elements = my_list[:n]
print(first_n_elements)
[10, 20, 30, 40]

In the above example, list slicing is used to get a list’s first n elements. As we can see, a list was defined as my_list with 6 elements [10, 20, 30, 40, 50, 60]. And a variable n was defined with a value of 4, representing the number of elements to be extracted from the list.

To obtain the first n elements, list slicing was used by specifying the start index as 0 (which was the default) and the end index as n. As a result, a new list was obtained, named first_n_elements, which contained the first n elements of my_list.

Using List Comprehension

Use list comprehension to create a list with the first n elements in Python.

original_list = ['India', 'China', 'Bhutan', 'Nepal', 'Thailand', 'France']
n = 3
new_list = [original_list[i] for i in range(n)]
print(new_list)
['India', 'China', 'Bhutan']

In this example, list comprehension creates a list with the first n elements. An original list was defined as original_list with six elements. And a variable n was defined with a value of 3, representing the number of elements extracted from the original list.

Then a list comprehension expression inside the square brackets [ ] was used to create a new list containing elements from the original list with an index between 0 and n-1. As a result, a new list was obtained and named new_list, which contained the original list’s first 3 elements.

Using the itertools Module

Use the itertools module in python to get the list’s first n elements by combining the islice and iter functions from the module.

import itertools
original_list = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'sat']
n = 5
first_n_elements = list(itertools.islice(iter(original_list ), n))
print(first_n_elements)
['Sun', 'Mon', 'Tues', 'Wed', 'Thurs']

In the above code, the itertools module is used. An original list was defined as original_list with 7 elements representing weekdays, and variable n was defined with a value of 5, which meant the number of elements to be extracted from the original list. To get the list’s first n elements, the islice function from the itertools module was used.

The islice function took two arguments, as we can see islice(iter(original_list ), n):

  • An iterator.
  • The number of elements to return.

An iterator iter(original_list ) was created from the original list using the iter function, and then the iterator and the value of n were passed to the islice function. As a result, a new list was obtained and named first_n_elements, which contained the first 5 elements of the original list we wanted to extract.

if you want to get more information about the itertools module, check its official documentation in python.

Using for Loop

Use the for loop to get a list’s first n elements in Python.

original_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
n = 2
first_n_elements = []
for i in range(n):
    first_n_elements.append(original_list[i])
print(first_n_elements)
['one', 'two']

To get the list’s first n elements, we used a for loop in the above example that iterated over a range of numbers from 0 to n-1. We appended the element at the corresponding index in the original list to the first_n_elements list during each iteration. After the loop is completed, the first_n_elements list contains the first 2 elements of the original list, which were ['one', 'two'].

Using While Loop

Use the While loop to get the first n elements of a list in Python.

my_list = [1, 2, 3, 4, 5, 6]
n = 3
i = 0
new_list = []
while i < n:
    new_list.append(my_list[i])
    i += 1
print(new_list)
[1, 2, 3]

The above code snippet used a while loop to extract the specified number of elements from a list and store them in a new list. A list named my_list is defined as containing the values [1, 2, 3, 4, 5, 6] and a variable n representing the number of elements we wanted to extract from my_list.

Next, two variables, i and new_list, were initialized to 0 and an empty list [], respectively. These variables were used to keep track of the current index of the element in the list and the extracted elements.

Then, a while loop would continue as long as the value of i was less than n. Inside the loop, the current element of my_list at index i was extracted and appended to the new_list. The value of i was then incremented by 1 to move on to the next element. Once the while loop was exited, the extracted elements in new_list were printed out using the print() function as [1, 2, 3].

That’s all about how to get first n elements of List in Python.

]]>
https://java2blog.com/get-first-n-elements-of-list-python/feed/ 0
Repeat List N Times in Python https://java2blog.com/repeat-list-n-times-python/?utm_source=rss&utm_medium=rss&utm_campaign=repeat-list-n-times-python https://java2blog.com/repeat-list-n-times-python/#respond Mon, 26 Dec 2022 06:41:38 +0000 https://java2blog.com/?p=21847 This tutorial will demonstrate how to repeat list n times in Python.

Using the * operator

To repeat list n times in Python, use the * operator. Star operator(*) is used to multiply list by number e.g. lst*3 and this will repeat list 3 times.

See the code below.

lst = [2, 4, 6, 11]
lst_new = lst * 3
print(lst_new)

Output:

[2, 4, 6, 11, 2, 4, 6, 11, 2, 4, 6, 11]

In the above example, we demonstrate the use of the * operator to repeat list n times in Python. This will repeat the elements of the list the required number of times.

Using the numpy.repeat() function

To repeat list n times in Python:

  • Use the numpy.repeat() function to repeat every element n times in Python.

See the code below.

import numpy as np
lst = [2, 4, 6, 11]
lst_new = list(np.repeat(lst,3))
print(lst_new)

Output:

[2, 2, 2, 4, 4, 4, 6, 6, 6, 11, 11, 11]

The numpy.repeat() function repeats the elements of the array. It will repeat the elements individually the required number of times and return a numpy array.

We can convert this array back to a list using the list() function.

Using the list comprehension technique

To repeat list n times in Python:

  • Use the for loop to iterate over the list elements and create a new list using list comprehension.
  • Use another for loop to iterate over every element and repeat it the required number of times.

See the code below.

lst = [2, 4, 6, 11]
lst_new = [a for a in lst for i in range(3)]
print(lst_new)

Output:

[2, 2, 2, 4, 4, 4, 6, 6, 6, 11, 11, 11]

List comprehension is an elegant way to create lists using the for loop in a single line of code.

To repeat list n times in Python, we use two loops in list comprehension.

The first loop iterates over every element and the second loop will repeat it the required number of times.

Using the itertools.repeat() function

To repeat list n times in Python:

  • Use the itertools.repeat() function to repeat elements from an iterable.
  • Use the itertools.from_iterable() function to return a flattened iterable from the input.

See the code below.

import itertools
lst = [2, 4, 6, 11]
lst_new = list(itertools.chain.from_iterable(itertools.repeat(i, 3) for i in lst))
print(lst_new)

Output:

[2, 2, 2, 4, 4, 4, 6, 6, 6, 11, 11, 11]

The itertools library is used to work with complex iterables efficiently in Python.

We can use the itertools.repeat() method to repeat the elements of a list and flatten it using the from_iterable() function.

Conclusion

To conclude, we discussed several methods to repeat list n times in Python.

In the first method, we used the * operator to repeat a list the required number of times. In the following method, the numpy.repeat() function was used to repeat individual elements of the list.

We demonstrated the use of the list comprehension technique to create a new list by using two successive for loops. The first loop will create a new list of the elements from the original list and the second loop will repeat these elements.

In the final method, we discussed the use of the itertools library that can be used to deal with complex iterables in Python. We used the itertools.repeat() and itertools.chain.from_iterable() functions in this method.

That’s all about how to repeat List N time in Python.

]]>
https://java2blog.com/repeat-list-n-times-python/feed/ 0
Convert List to Comma Separated String in Python https://java2blog.com/convert-list-to-comma-separated-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=convert-list-to-comma-separated-string-python https://java2blog.com/convert-list-to-comma-separated-string-python/#respond Fri, 16 Dec 2022 18:24:32 +0000 https://java2blog.com/?p=21833 Use .join() Method

To convert a list to a comma separated string in Python, use the .join() method. join() method takes all elements in an iterable and joins them into one string with delimiter as separator.

list_of_strings = ['string_one', 'string_two', 'string_three']
comma_separated_strings = ','.join(list_of_strings)
print(comma_separated_strings)
string_one,string_two,string_three

First, we created a list having string-type elements and named that list list_of_strings. Next, we used the .join() method to join all list elements into strings using a comma as a separator. This method took an iterable as a parameter, which is list_of_strings, for this code example.

Here, iterable means the objects which can return their members/elements one at a time. We used a comma as a separator, but you can use a separator of your choice; it can be #, whitespace, etc.

Suppose the list contains non-string elements, such as int, bool, None, etc. Now, using the .join() method only will result in an error saying TypeError: sequence item 1: expected str instance, int found.

To handle this scenario, we can use the .join() with the map() method, as demonstrated in the following section.

Use .join() with map() Method

To convert a list having string and integer type elements to a comma separated strings in Python:

  • Use the map() method to transform the data type of all list elements to string.
  • Use the .join() method to join all the list elements (now of string data type) and separate them with a comma.
list_of_alphanumeric = ['string_one', 10, 'string_two', 'string_three']
comma_separated_strings = ','.join(map(str, list_of_alphanumeric))
print(comma_separated_strings)
string_one,10,string_two,string_three

In the previous section, we learned about the .join() method while converting a list_of_strings to comma-separated strings. Here, we used the map() method to map every list element to a string type value.

Once the mapping is performed on all list elements, we pass this map type object to the .join() method to join them separated by a comma.

Here, map(str, list_of_alphanumeric) maps the type of every element of list_of_alphanumericlist where every element is passed to str() function as its parameter.

Use .join() with List Comprehension

There is an alternative of using .join() with map() method, which is using .join() method with list comprehension as follows:

  • Use a list comprehension to iterate over each element of the list. In each iteration, pass the list element to str() for type casting.
  • Once all elements are cast to string data type, pass the converted list to the .join() method to join all the list elements separated by a comma.
list_of_alphanumeric = ['string_one', 10, 'string_two', 'string_three']
comman_separated_strings = ','.join([str(x) for x in list_of_alphanumeric])
print(comman_separated_strings)
string_one,10,string_two,string_three

After creating a list, we used list comprehension, which looped over the elements of the list_of_alphanumeric. Finally, we passed the current element to the str() method for type casting in each iteration. Here, type casting means changing the element’s datatype from one another.

Next, we passed the transformed list having all string-type elements to the .join() method, which joins all the elements by separating them using the given separator. We used , as the separator; you can use whatever you want.

That’s all about how to convert list to comma separated Strings in Python.

]]>
https://java2blog.com/convert-list-to-comma-separated-string-python/feed/ 0
Remove Punctuation from List in Python https://java2blog.com/remove-punctuation-from-list-python/?utm_source=rss&utm_medium=rss&utm_campaign=remove-punctuation-from-list-python https://java2blog.com/remove-punctuation-from-list-python/#respond Sun, 27 Nov 2022 07:33:56 +0000 https://java2blog.com/?p=21353 Use for loop with replace() Method

To remove punctuation from list in Python:

  • Use the for loop to iterate over each word (element) of given list.
  • Use a nested loop to iterate over each character in the word.
  • Use the if statement to check if the current character is in string.punctuation, if it is use replace() to replace punctuation marks with an empty string.
  • After iterating over the each word, use append() to append the word into the new_list.
import string

my_list = ["How's", "Hello,", "Goodbye!", "Take Care", ""]
new_list = []
for word in my_list:
    for character in word:
        if character in string.punctuation:
            word = word.replace(character,"")   
    new_list.append(word)

print(new_list)

We will get the below output on the successful execution of the above program.

['Hows', 'Hello', 'Goodbye', 'Take Care', '']

We used a for loop to iterate over all the elements of the list.

The nested for loop is used to iterate over each word character by character.

We checked if the character is in string.puntucation, if it is so then, used the replace() method to replace the punctuation character with an empty string.

In Python, the string.puncutation is the pre-initialized string which has all the punctuation marks, we can also use print them as print(string.punctuation) to have a look at all the punctuation marks.

The replace() method takes two phrases where the first pattern/phrase is replaced with the second pattern/phrase.

By default, the replace() function replaces all the occurrences but we can also pass a count to remove punctuation from the first n elements of a list.

Once we have iterated over the word, use the append() method to append word to the my_list.

Here, we used the append() method to append elements to the end of the list, which is new_list in our case. Finally, we used a print statement to print the updated list.

You may have noticed that we had an empty string in the above output that is not required. For that, we can add another condition to assess if the current element is an empty string or not.

If it is so, we can remove that element from the list; otherwise jump to the else part.

import string

my_list = ["How's", "Hello,", "Goodbye!", "Take Care", ""]
new_list = []

for word in my_list:
    if word =="":
        my_list.remove(word)
    else:
        for character in word:
            if character in string.punctuation:
                word = word.replace(character,"")   
        new_list.append(word)

print(new_list)

Now, we will get the following outcome.

['Hows', 'Hello', 'Goodbye', 'Take Care']

This code is similar to the first code example but we used the if-else statement to check if the word is an empty string or not.

If it is then, we used the remove() function to eliminate the specified word from the list; otherwise, moved ahead to the else section.

Use Nested List Comprehension

To remove punctuation from the given list in Python:

  • Use an inner for loop to iterate over each word character by character and check if that character belongs to string.punctuation.
    Use str.join() to join all the characters returned by the above loop with the empty string and produce a whole word which does not has any punctuation signs.
  • Use an outer for loop to execute the inner list comprehension for every word inside the my_list list.
  • Store all the words returned by the outer list comprehension into a new_list list.
import string
my_list = ["How's", "Hello,", "Goodbye!", "Take Care", ""]

new_list = [''.join(character for character in word
               if character not in string.punctuation)
               for word in my_list]
print(new_list)

We will get the following list after running the above program.

['Hows', 'Hello', 'Goodbye', 'Take Care', '']

Usually, this code seems difficult to understand to most people but let’s break it down into chunks to understand.

The above code is using nested list comprehension which has two sections, the inner and outer parts.

The ''.join(character for character in word if character not in string.punctuation) is the inner part while for word in my_list is the outer part of list comprehension. Here, the outer part runs the inner part as follows.

In the inner part, we used a for loop to iterate over each word letter by letter and make sure that the character is not in string.punctuation.

The str.join() wrapping the inner part joined all the returned characters with the empty string.

In the outer part, we used a for loop to execute the inner part for every word in my_list and save the returned words (without punctuation signs) in new_list.

Finally, we used the print statement to display the results on the console.

This approach is preferable where we’ve limited memory space because list comprehension not only serves the same results with fewer lines of code but lets us perform inplace modifications. It means, we don’t have to create new lists but we can update the original list.

Notice that we are again having an empty string in the above output that we can remove by using an additional if statement in the outer part of the list comprehension as follows.

import string
my_list = ["How's", "Hello,", "Goodbye!", "Take Care", ""]

new_list = [''.join(character for character in word
              if character not in string.punctuation)
              for word in my_list
              if word]
print(new_list)

The above program will show the following output.

['Hows', 'Hello', 'Good bye', 'Take Care']

Use str.translate() Function

To eliminate punctuation signs from the given list in Python:

  • Use the str.translate() function with pre-initialized string.punctuation constant and list comprehension.
import string
my_list = ["How's", "Hello,", "Goodbye!", "Take Care", ""]
new_list = [word.translate(string.punctuation) for word in my_list]
print(new_list)

We will get the following results after running the above code fence successfully.

["How's", 'Hello,', 'Goodbye!', 'Take Care', '']

Using str.translate() is much easier to understand and faster in terms of execution as compared to the last two approaches.

The list comprehension executed the word.translate(string.punctuation) for each word in my_list while the str.translate(string.punctuation) mapped each character in string.punctuation to an empty string.

Note that, the str.translate(string.punctuation) mapped each character for every word in my_list.

Finally, we saved all the returned elements by list comprehension in new_list and display them on the screen.

We can also add an if statement to remove the empty string from the output.

import string
my_list = ["How's", "Hello,", "Goodbye!", "Take Care", ""]
new_list = [word.translate(string.punctuation) for word in my_list if word]
print(new_list)
["How's", 'Hello,', 'Goodbye!', 'Take Care']

That’s all about how to remove punctuation from List in Python.

]]>
https://java2blog.com/remove-punctuation-from-list-python/feed/ 0
Add Tuple to List in Python https://java2blog.com/add-tuple-to-list-python/?utm_source=rss&utm_medium=rss&utm_campaign=add-tuple-to-list-python https://java2blog.com/add-tuple-to-list-python/#respond Fri, 23 Sep 2022 07:52:12 +0000 https://java2blog.com/?p=20258 Add tuple to list in Python

Tuples and Lists are two of the most commonly used collection objects in Python. They both can store multiple elements and provide access to these elements using their indexes. There are a few differences associated with them as well.

Tuples are immutable, which means that once created they cannot be changed. Due to this, they require less memory and provide faster access to elements. Lists on the other hand are mutable and dynamic. They require more memory and access to elements is comparatively slow.

We will now discuss how to add tuple to list in Python.

Ways to Add Tuple to List in Python (adding the Tuple as An Element)

In this section of the article, we will discuss how to add a tuple as an element to the list.

Using the insert() Function to Add Tuple to List in Python

The insert() function can be used to add elements to a list at some specific position. We can provide the desired element along with the index in the function.

To add tuple to list in Python, we will provide the tuple as the element within the function.

See the code below.

lst = [(1,3),(7,8)]
t = (5,6)
lst.insert(1,t)
print(lst)

Output:

[(1, 3), (5, 6), (7, 8)]

In the above example, we had a list of tuples, and we added a tuple to this list using the insert() function.

Using the append() Function to Add Tuple to List in Python

The append() function is used to add elements towards the end of the list. We can specify the element within the function. In our example, we will add tuple to list in Python by specifying the tuple within the function.

For example,

lst = [(1,3),(7,8)]
t = (5,6)
lst.append(t)
lst

Output:

[(1, 3), (7, 8), (5, 6)]

Ways to Add Tuple to List in Python (adding the Tuple’s Elements to A List)

In this section of the article, we will insert the elements of a tuple into a given list. Several methods are discussed below.

Using the extend() Function to Add Tuple to List in Python

The extend() function accepts an iterable and adds its elements to the end of a list. We can specify the tuple in the function to add tuple to list in Python.

lst = [1,3,7,8]
t = (5,6)
lst.extend(t)
print(lst)

Output:

[1, 3, 7, 8, 5, 6]

In the above example, we add the elements from the tuple to the list using the extend() function.

Using the += Operator to Add Tuple to List in Python

The += operator is termed as the concatenation operator that can combine elements from two iterables. We can add tuple to list in Python using this operator.

Remember that this operator only works for non-local objects (A variable that is not global nor local to a particular function).

See the code below.

lst = [1,3,7,8]
t = (5,6)
lst += t
print(lst)

Output:

[1, 3, 7, 8, 5, 6]

Conclusion

To conclude, we discussed how to add tuple to list in Python. This was discussed in two sections.

In the first section, we discussed how to add a tuple as an element to the list. For this, we used the insert() function that can add elements at a given index in a list and the append() function that adds elements to the end of a list.

In the second section, we discussed how to add the tuple’s elements to a given list, essentially combining them both. The first method involved the use of the extend() function and we used the concatenation operator (+=) in the second method. Both perform the same function without much time difference.

That’s all about how to add tuple to list in Python.

]]>
https://java2blog.com/add-tuple-to-list-python/feed/ 0
Replace Comma with Space in List in Python https://java2blog.com/replace-comma-with-space-in-list-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=replace-comma-with-space-in-list-in-python https://java2blog.com/replace-comma-with-space-in-list-in-python/#respond Tue, 24 May 2022 18:19:19 +0000 https://java2blog.com/?p=20125 In this post, we will see how to replace comma with space in the list.

How to replace comma with space in list in Python

A list is one of the fundamental collection objects in Python. It can store multiple elements and we can access these elements using their respective index. When we display a list, every element is separated with a comma.

In this article, we will discuss how to replace comma with space in list in Python. Note that we cannot directly replace the comma while displaying a list. So in our methods, we will convert the list to a string and then replace the comma with space in list in Python.

The methods are discussed below.

Using the replace() function to replace comma with space in list in Python

In Python, we can replace substrings within a string using the replace() function. Using this function, we can replace comma with space in list in Python. It returns a new string with the substituted substring.

But first, remember that we need to get the string representation of the list. We can achieve this using the str() function.

See the code below.

lst = [11,33,22,99]
s = str(lst)
s = s.replace(',', ' ')
print(s)

Output:

[11 33 22 99]

In the above example, we replace comma with space in list in Python. We first converted the list to a string using the str() function. Then we replaced the commas with space using the replace() function.

Using the re.sub() function to replace comma with space in list in Python

Regular expressions are an elegant way to match parts of strings using regex patterns. In Python, we can use the re module to work with regular expressions.

The re.sub() function can be used to replace a given substring that matches some regex pattern. We can use it to replace comma with space in list in Python. For our case, we use it without any regex pattern and directly mention commas in the function.

See the code below.

import re
lst = [11,33,22,99]
s = str(lst)
s = re.sub(',', ' ',s)
print(s)

Output:

[11 33 22 99]

Using the split() and join() functions to replace comma with space in list in Python.

The split() function is used to split a string into a list of substrings by splitting it based on a character. The join() function is used in Python to combine the elements from an iterable as a string.

First, we will convert the list to a string as done in previous methods. We will then split the string based on the comma using the split() function. Then the elements are combined using the join() function. The space is used as a separator character in the join() function.

See the code below.

import re
lst = [11,33,22,99]
s = str(lst)
s = ''.join(i for i in s.split(','))
print(s)

Output:

[11 33 22 99]

In the above example, we first split the string to a list and then combine it again to replace comma with space in list in Python.

Conclusion

To conclude, we discussed how to replace comma with space in list in Python. The first two methods were very straightforward.

We converted the list to a string and replaced the comma with space using the replace() and re.sub() functions.

In the final method, we used two functions to split the string into a list again and then use the join() function to combine the elements using the space character as the separator.

That’s all about how to replace comma with space in List in Python

]]>
https://java2blog.com/replace-comma-with-space-in-list-in-python/feed/ 0