How do i print only numbers in a list in python?

All solutions proposed work only if the numbers inside the list are already converted to the appropriate type [int, float].

I found myself with a list coming from the fetchall function of sqlite3. All elements there were formated as str, even if some of those elements were actually integers.

cur.execute['SELECT column1 FROM table1 WHERE column2 = ?', [some_condition, ]]
list_of_tuples = cur.fetchall[]

The equivalent from the question would be having something like:

list_1 = [ 'asdada', '1', '123131', 'blaa adaraerada', '0', '34', 'stackoverflow is awesome' ]

For such a case, in order to get a list with the integers only, this is the alternative I found:

list_of_numbers = []
for tup in list_of_tuples:
    try:
        list_of_numbers.append[int[tup[0]]]
    except ValueError:
        pass

list_of_numbers will contain only all integers from the initial list.

If you have a list in Python that contains both integer and non-integer values, and you want to create a new list that contains only the integer values, there are a few ways you can do this. One way is to use a list comprehension, which is a powerful tool for creating lists based on other lists. Another way is to use the built-in function isinstance[], which allows you to check if a value is an integer.

Get integer values from a list using isinstance[] function and list comprehension

List comprehension is a powerful tool for working with lists. It allows you to easily get integer values from a list, without having to write multiple lines of code. In this article, we'll show you how to use list comprehension to get integer values from a list.

my_list = ["a", 1, "b", 2, 3, 4, "c", "d"]

result = [val for val in my_list if isinstance[val, [int, float]]]

print[result]

Output

[1, 2, 3, 4]
  1. The code creates a list called my_list with a mix of strings and integers.
  2. It then iterates through each value in my_list using a For loop.
  3. For each value, it checks if the value is an instance of either the int or float class.
  4. If the value is an instance of either int or float, it is added to a new list called result.
  5. Finally, the code prints out the contents of the result.

You can also import the numbers module and use them in instance[] function. Check the below example.

import numbers

my_list = ["a", 1, "b", 2, 3, 4, "c", "d"]

result = [val for val in my_list if isinstance[val, numbers.Number]]

print[result]

Output

[1, 2, 3, 4]

The above code example is using a list comprehension to create a new list. The new list will contain all of the values from the original list that are instances of the numbers.Number class.

Get integer values from a list using isdigit[] function and list comprehension [If all values are in string format]

Python's built-in isdigit[] function can be used to check if a string is an integer. This function is used in conjunction with a list comprehension to get a list of all integers in a given list.

In the below code example we have all values in string format and we want to extract the number values from it.

my_list = ["a", "1", "b", "2", "3", "4", "c", "d"]

result = [val for val in my_list if val.isdigit[]]

print[result]

Output

['1', '2', '3', '4']

Walkthrough:

  1. The code creates a list called my_list.
  2. The code then creates a new list called result.
  3. The code looks through each value in my_list and sees if it is a digit.
  4. If the value is a digit, it is added to the result list.
  5. The code then prints the result list.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Printing a list in python can be done is following ways:

    • Using for loop : Traverse from 0 to len[list] and print all elements of the list one by one using a for loop, this is the standard practice of doing it. 

    Python

    a = [1, 2, 3, 4, 5]

    for x in range[len[a]]:

        print a[x],

    • Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively. 

    Python

    a = [1, 2, 3, 4, 5]

    print[*a]

    print["printing lists separated by commas"]

    print[*a, sep = ", "

    print["printing lists in new line"]

    print[*a, sep = "\n"]

    Output

    1 2 3 4 5
    printing lists separated by commas
    1, 2, 3, 4, 5
    printing lists in new line
    1
    2
    3
    4
    5
    

    • Convert a list to a string for display : If it is a list of strings we can simply join them using join[] function, but if the list contains integers then convert it into string and then use join[] function to join them to a string and print the string. 

    Python

    a =["Geeks", "for", "Geeks"]

    print[' '.join[a]]

    a = [1, 2, 3, 4, 5]

    print str[a][1:-1

    Output

    Geeks for Geeks
    1, 2, 3, 4, 5
    

    • Using map : Use map[] to convert each item in the list to a string if list is not a string, and then join them: 

    Python

    a = [1, 2, 3, 4, 5]

    print[' '.join[map[str, a]]] 

    print"in new line"

    print['\n'.join[map[str, a]]]

    Output

    1 2 3 4 5
    in new line
    1
    2
    3
    4
    5
    

    • Using list comprehension : Use list comprehension to go one by one to each element in list and print. 

    Python3

    a = [1, 2, 3, 4, 5]

    [print[i, end=' '] for i in a] 

    print["\nIn new line"]

    [print[i] for i in a]

    Output

    1 2 3 4 5 
    In new line
    1
    2
    3
    4
    5
    


    How do I print only numbers in Python list?

    “how to extract numbers from a list in python” Code Answer.
    a = ['1 2 3', '4 5 6', 'invalid'].
    numbers = [].
    for item in a:.
    for subitem in item. split[]:.
    if[subitem. isdigit[]]:.
    numbers. append[subitem].
    print[numbers].

    How do you print the number of elements in a list?

    The most straightforward way to get the number of elements in a list is to use the Python built-in function len[] . As the name function suggests, len[] returns the length of the list, regardless of the types of elements in it.

    How do you filter numbers in a list in Python?

    Python has a built-in function called filter[] that allows you to filter a list [or a tuple] in a more beautiful way. The filter[] function iterates over the elements of the list and applies the fn[] function to each element. It returns an iterator for the elements where the fn[] returns True .

    How do you select a number in a list in Python?

    To select elements from a Python list, we will use list. append[]. We will create a list of indices to be accessed and the loop is used to iterate through this index list to access the specified element.

    Chủ Đề