Python check all elements in list are string

If I have a list in python, is there a function to tell me if all the items in the list are strings?

For Example: ["one", "two", 3] would return False, and ["one", "two", "three"] would return True.

asked May 21, 2016 at 0:49

1

Just use all[] and check for types with isinstance[].

>>> l = ["one", "two", 3]
>>> all[isinstance[item, str] for item in l]
False
>>> l = ["one", "two", '3']
>>> all[isinstance[item, str] for item in l]
True

answered May 21, 2016 at 0:50

TigerhawkT3TigerhawkT3

47.5k6 gold badges56 silver badges89 bronze badges

3

Answering @TekhenyGhemor's follow-up question: is there a way to check if no numerical strings are in a list. For example: ["one", "two", "3"] would return false

Yes. You can convert the string to a number and make sure that it raises an exception:

def isfloatstr[x]:
    try: 
        float[x]
        return True
    except ValueError:
        return False

def valid_list[L]:
    return all[[isinstance[el, str] and not isfloatstr[el]] for el in L]

Checking:

>>> valid_list[["one", "two", "3"]]
False

>>> valid_list[["one", "two", "3a"]]
True

>>> valid_list[["one", "two", 0]]
False

In [5]: valid_list[["one", "two", "three"]] Out[5]: True

answered May 21, 2016 at 4:39

NeapolitanNeapolitan

2,0018 silver badges20 bronze badges

Another way to accomplish this is using the map[] function:

>>> all[map[lambda x: isinstance[x, str], ['one', 'two', 3]]]
False
>>> all[map[lambda x: isinstance[x, str], ['one', 'two', 'three']]]
True

answered Mar 13 at 3:16

In this article we will dicuss different ways to check if all element in a given List are same or matches a condition.

Suppose we have a list of string i.e.

# List of string 
listOfStrings = ['Hello'] * 10

Now let’s use python all[] function to check if all elements in the given list are same.

Python : all[] function

Python all[] function checks if all Elements of given Iterable is True.

check if element are same using all[]

Let’s convert the list to Iterable and check if each entry of iterable is equal to first element of list using all[] i.e.

'''    
    check if element are same using all[]
    It will Iterate through all the elements in list and check if all elements are similar to first element or not.
'''
result = False;
if len[listOfStrings] > 0 :
    result = all[elem == listOfStrings[0] for elem in listOfStrings]

if result :
    print["All Elements in List are Equal"]
else:        
    print["All Elements in List are Not Equal"]

Advertisements

count[] returns the occurrence count of given element in the list.

Let’s call the count[] function of list with firts element of list as argument. If its occurrence count is equal to the length of list, then it means all elements in list are Same i.e.

'''    
    check if element are same using list.count[]
    If occurence count of first element in list is equal to length of list.
    Then it means all elements in List are equal 
'''
result = False;
if len[listOfStrings] > 0 :
    result = listOfStrings.count[listOfStrings[0]] == len[listOfStrings]

Let’s do the same thing in single line i.e.

result = len[listOfStrings] > 0 and all[elem == listOfStrings[0] for elem in listOfStrings]

Check if all elements are same using Set

As set contains only unique elements, so convert the list to set. If set size is 1 then it means all elements in given list are same i.e.

'''    
    As set contains unique elements only, so if list has similar elements, then only one will stored in set.
'''    
result = len[set[listOfStrings]] == 1

Complete example is as follows,

def main[]:
    
    # List of string 
    listOfStrings = ['Hello'] * 10
    
    # Print the List
    print[listOfStrings]
    
    '''    
        check if element are same using all[]
        It will Iterate through all the elements in list and check if all elements are similar to first element or not.
    '''
    result = False;
    if len[listOfStrings] > 0 :
        result = all[elem == listOfStrings[0] for elem in listOfStrings]    
    
    if result :
        print["All Elements in List are Equal"]
    else:        
        print["All Elements in List are Not Equal"]
    
    '''    
        check if element are same using list.count[]
        If occurence count of first element in list is equal to length of list.
        Then it means all elements in List are equal 
    '''
    result = False;
    if len[listOfStrings] > 0 :
        result = listOfStrings.count[listOfStrings[0]] == len[listOfStrings]
        
    if result :
        print["All Elements in List are Equal"]
    else:        
        print["All Elements in List are Not Equal"]
        
        
    # Do the above logic in single line    
    result = len[listOfStrings] > 0 and all[elem == listOfStrings[0] for elem in listOfStrings] 
       
    if result :
        print["All Elements in List are Equal"]
    else:        
        print["All Elements in List are Not Equal"]      
    
    
    '''    
        As set contains unique elements only, so if list has similar elements, then only one will stored in set.
    '''    
    result = len[set[listOfStrings]] == 1   
    
    if result :
        print["All Elements in List are Equal"]
    else:        
        print["All Elements in List are Not Equal"]      
         
if __name__ == '__main__':
    main[]

Output:

['Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello', 'Hello']
All Elements in List are Equal
All Elements in List are Equal
All Elements in List are Equal
All Elements in List are Equal

 

How do you check if all elements in a list are strings Python?

Just use all[] and check for types with isinstance[] . @TekhenyGhemor - isinstance[item, str] and not item. lstrip['-']. isdigit[] for zero or positive integers.

How do you check all items in a list Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count[] function.

How do you check if all elements in a string are numbers?

The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.

How do you check if all elements in a list are numeric Python?

Python String isnumeric[] Method The isnumeric[] method returns True if all the characters are numeric [0-9], otherwise False.

Chủ Đề