Question
- Given two lists, l1 and l2, write a program to create a third list l3 by picking an odd-index element from the list l1 and even index elements from the list l2.
Given:
l1 = [3, 6, 9, 12, 15, 18, 21] l2 = [4, 8, 12, 16, 20, 24, 28]
Expected Output:
Element at odd-index positions from list one [6, 12, 18] Element at even-index positions from list two [4, 12, 20, 28] Printing Final third list [6, 12, 18, 4, 12, 20, 28]
My solution
- use the list comprehension
- use enumerate() function to generate index and value for each element in each list
- find the remainder of the index divided by two
- if remainder is not zero mean an odd index
- i.e. "if index % 2" is not equal to 0, so it would equal to True
- if the remainder is zero mean an even index
- i.e. if index % 2 is 0, so would equal to false
- list comprehension only accept True condition,
- so "not index % 2" is used
- if remainder is not zero mean an odd index
l1 = [3, 6, 9, 12, 15, 18, 21] l2 = [4, 8, 12, 16, 20, 24, 28] odd_index_list = [num for index, num in enumerate(l1) if index % 2] print("Element at odd-index positions from list one") print(odd_index_list) even_index_list = [num for index, num in enumerate(l2) if not index % 2] print("Element at even-index positions from list two") print(even_index_list) final_list = odd_index_list + even_index_list print("Printing Final third list") print(final_list)
Other solution
- use string slicing method
- for odd elements slice the string from index 1 to the end with a step of 2
- for even elements slice the string form index 0 to the end with a step of 2
list1 = [3, 6, 9, 12, 15, 18, 21] list2 = [4, 8, 12, 16, 20, 24, 28] res = list() odd_elements = list1[1::2] print("Element at odd-index positions from list one") print(odd_elements) even_elements = list2[0::2] print("Element at even-index positions from list two") print(even_elements) print("Printing Final third list") res.extend(odd_elements) res.extend(even_elements) print(res)
Credit
exercise on Pynative
Top comments (0)