![]() |
VOOZH | about |
Sometimes, while working with Python lists, we can have a subproblem in which we need to tie a particular element with each of the list elements. This task can have its utility in the web development domain while working with queries and filters. Let's discuss ways to solve this problem.
Method 1: Using zip() + repeat() This problem can be solved using zip() which can be used to attach to each list element with a decided number using repeat().
The original list is : [5, 6, 7, 8, 4, 3] Tuple list after attaching element : [(5, 'gfg'), (6, 'gfg'), (7, 'gfg'), (8, 'gfg'), (4, 'gfg'), (3, 'gfg')]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using map() + lambda This is yet another way in which this task can be performed. In this, we just extend the logic of adding element to list element to all elements using map(), by feeding it with lambda function to perform computation tasks.
The original list is : [5, 6, 7, 8, 4, 3] Tuple list after attaching element : [(5, 'gfg'), (6, 'gfg'), (7, 'gfg'), (8, 'gfg'), (4, 'gfg'), (3, 'gfg')]
Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(n), as the list of bi-tuples is created which takes up n elements.
Method #3: Using append() method
The original list is : [5, 6, 7, 8, 4, 3] Tuple list after attaching element : [(5, 'gfg'), (6, 'gfg'), (7, 'gfg'), (8, 'gfg'), (4, 'gfg'), (3, 'gfg')]
Time complexity: O(n), where n is the length of the input list 'test_list'. This is because the for loop iterates through all the elements of the list once.
Auxiliary space: O(n), where n is the length of the input list 'test_list'.
Method #4: Using list comprehension
This approach uses list comprehension to iterate over the elements of the input list and attach the element ele to each of them, creating a new list of tuples.
Example:
The original list is : [5, 6, 7, 8, 4, 3] Tuple list after attaching element : [(5, 'gfg'), (6, 'gfg'), (7, 'gfg'), (8, 'gfg'), (4, 'gfg'), (3, 'gfg')]
Time complexity: O(N) - the time it takes to iterate through the entire list once and create a new tuple for each element.
Auxiliary space: O(N) - the space used to create the new list of tuples, which is equal to the size of the original list.
Method #5: Using itertools cycle:
The original list is : [5, 6, 7, 8, 4, 3] Tuple list after attaching element : [(5, 'gfg'), (6, 'gfg'), (7, 'gfg'), (8, 'gfg'), (4, 'gfg'), (3, 'gfg')]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: using a for loop
Approach:
Example:
The original list is : [5, 6, 7, 8, 4, 3] Tuple list after attaching element : [(5, 'gfg'), (6, 'gfg'), (7, 'gfg'), (8, 'gfg'), (4, 'gfg'), (3, 'gfg')]
Time Complexity: O(n) (where n is the length of the list)
Auxiliary Space: O(n) (for the result list)