Saturday, November 23, 2024
Google search engine
HomeLanguagesPython – Elements Lengths in List

Python – Elements Lengths in List

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments