Open In App

Python – Elements Lengths in List

Last Updated : 01 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, can have problem in which we need to count the sizes of elements that are part of lists. This is because list can allow different element types to be its members. This kind of problem can have application in many domains such has day-day programming and web development. Lets discuss certain ways in which we can perform this task. 

Method #1 : Using loop This is brute way in which this task can be performed. In this, we iterate for each loop element and find its size using elements counter. 

Python3




# Python3 code to demonstrate working of
# Elements Lengths in List
# Using loop
 
# initializing list
test_list = ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Elements Lengths in List
# Using loop
res = []
for ele in test_list:
    count = 0
    if type(ele) == int:
        res.append(1)
    else :
        for sub in ele:
            count = count + 1
        res.append(count)
 
# printing result
print("The element sizes in order are : " + str(res))


Output : 

The original list is : ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
The element sizes in order are : [3, 3, 1, 4, 4]

Time Complexity: O(n) where n is the total number of values in the list “test_list”. 
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”. 

Method #2 : Using list comprehension + len() This task can also be performed using list comprehension. In this, we compute length using len() and iteration is performed using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Elements Lengths in List
# Using list comprehension + len()
 
# initializing list
test_list = ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Elements Lengths in List
# Using list comprehension + len()
res = [len(sub) if type(sub) != int else 1 for sub in test_list]
 
# printing result
print("The element sizes in order are : " + str(res))


Output : 

The original list is : ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
The element sizes in order are : [3, 3, 1, 4, 4]

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

Method #3 : Using len()+ append()

This method defines a function element_lengths that takes a list as input and returns a list of the lengths of the elements in the input list. The function loops through each element in the input list and checks its type using the isinstance function. If the element is a string, tuple, or list, the length of the element is appended to the result list. If the element is not a string, tuple, or list, 1 is appended to the result list. Finally, the result list is returned. The code also includes a couple of comments to explain what each part of the code is doing.

Python3




def element_lengths(test_list):
     # initialize an empty list to hold the lengths
     result = []
    # loop through each element in the input list
     for elem in test_list:
         # check if the element is a string
        if isinstance(elem, str):
          # if it is, append the length of the string to the result list
            result.append(len(elem))
        # check if the element is a tuple
        elif isinstance(elem, tuple):
            # if it is, append the length of the tuple to the result list
            result.append(len(elem))
        # check if the element is a list
        elif isinstance(elem, list):
            # if it is, append the length of the list to the result list
            result.append(len(elem))
        else:
            # if it's not a string, tuple, or list, append 1 to the result list
            result.append(1)
    # return the result list
     return result
test_list = ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
print(element_lengths(test_list))


Output

[3, 3, 1, 4, 4]

Time complexity: O(n)
Auxiliary Space: O(n)

Method #4 : Using numpy:

Algorithm:

1.Import the NumPy library.
2.Define the original list.
3.Print the original list.
4.Use a list comprehension to create a list of the lengths of each element in the original list, except for integers 5.which are represented as having a length of 1.
6.Convert the resulting list to a NumPy array.
7.Print the resulting array as a list using the tolist() method.

Python3




import numpy as np
 
# initializing list
test_list = ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Elements Lengths in List
# Using NumPy array
res = np.array([len(elem) if type(elem) != int else 1 for elem in test_list])
 
# printing result
print("The element sizes in order are : " + str(res.tolist()))
#This code  is contributed by Jyothi  pinjala


Output:

The original list is : ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
The element sizes in order are : [3, 3, 1, 4, 4]

Time complexity: The algorithm loops through each element of the input list once, so the time complexity is O(n), where n is the length of the input list.
Auxiliary Space: The algorithm creates a NumPy array to store the result, so the space complexity is O(n), where n is the length of the input list. However, since the size of the array is directly proportional to the size of the input list, we can consider the space complexity to be O(1) in terms of the size of the input list.

Method #5: Using map() function

Python3




# Python3 code to demonstrate working of
# Elements Lengths in List
# Using map() function
 
# initializing list
test_list = ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Elements Lengths in List
# Using map() function
res = list(map(lambda sub: len(sub) if type(sub) != int else 1, test_list))
 
# printing result
print("The element sizes in order are : " + str(res))


Output

The original list is : ['GFG', (4, 5, 6), 17, [5, 6, 7, 8], 'Best']
The element sizes in order are : [3, 3, 1, 4, 4]

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), as we are creating a new list of the same length as the input list.



Previous Article
Next Article

Similar Reads

Python | Split a list into sublists of given lengths
The problem of splitting a list into sublists is quite generic but to split in sublist of given length is not so common. Given a list of lists and list of length, the task is to split the list into sublists of given length. Example: Input : Input = [1, 2, 3, 4, 5, 6, 7] length_to_split = [2, 1, 3, 1] Output: [[1, 2], [3], [4, 5, 6], [7]] Method #1:
2 min read
Python - Value list lengths
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the length of list as tuple attribute. Let’s discuss certain ways in which this task can be performed. Method
5 min read
Python - List lengths as record attribute
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the lengths of list as tuple attribute. Let’s discuss certain ways in which this task can be performed. Method
3 min read
Python | Row lengths in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + map() + sum() + list comprehension The combination
4 min read
Python | Words lengths in String
We sometimes come through situations where we require to get all the word lengths present in the string, this can be a tedious task done using a naive method. Hence having shorthand to perform this task is always useful. Let's discuss certain ways to achieve this. Method #1 : Using split() + len() Using the split function, we can split the string i
5 min read
Python - Dictionary value lists lengths product
Given a dictionary with values as lists, compute the lengths of each list, and find product of all lengths. Input : test_dict = {'Gfg' : [6, 5, 9, 3], 'is' : [1, 3, 4], 'best' :[9, 16]} Output : 24 Explanation : 4 * 3 * 2 = 24. Length of lists are 4, 3, and 2. Input : test_dict = {'Gfg' : [6, 5, 3], 'is' : [1, 3, 4], 'best' :[9, 16]} Output : 18 Ex
4 min read
Python - Filter String Tuples if String lengths equals K
Given List of tuples, filter tuples, whose element strings have length equal to K. Input : test_list = [("ABC", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoOW")], K = 3 Output : [('ABC', 'Gfg', 'CS1')] Explanation : All Strings have length 3 in above tuple. Input : test_list = [("ABCD", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoOW")], K = 3 Output
6 min read
Python - Split a String by Custom Lengths
Given a String, perform split of strings on the basis of custom lengths. Input : test_str = 'geeksforgeeks', cus_lens = [4, 3, 2, 3, 1] Output : ['geek', 'sfo', 'rg', 'eek', 's'] Explanation : Strings separated by custom lengths.Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeksforge', 'eks'] Explanation : Strings separated by
2 min read
Python - Test for desired String Lengths
Given a String list, check for all string if it matches the desired string length from 2nd list of sizes. Input : test_list = ["Gfg", 'for', 'geeks'], len_list = [3, 3, 5] Output : True Explanation : All are of desired lengths. Input : test_list = ["Gfg", 'for', 'geek'], len_list = [3, 3, 5] Output : False Explanation : geek has len 4, but desired
6 min read
Python program to sort Dictionary by Key Lengths
Given Dictionary, sort by its key lengths. Input : test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3} Output : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3} Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order. Input : test_dict = {"Gfg" : 4, "for" : 3, "geeks" : 3} Output : {'Gfg': 4, 'for': 3, 'geeks': 3
4 min read
Practice Tags :
three90RightbarBannerImg