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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more