DEV Community

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

4 1

Python Exercise 10: Generate a list based on odd or even index

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Credit

exercise on Pynative

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs