Change language

Python | Separate odd and even index entries

| | |

Method # 1: Using the Naive Method

Using the Naive method, this task can be accomplished using loops. You can use two containers one at a time to hold alternate elements and then join them together.

# Python3 demo code
# Separate odd and even index items
# using a naive method

 
# initializing list

test_list = [ 3 , 6 , 7 , 8 , 9 , 2 , 1 , 5 ]

 
# print original list

print ( "The original list:" + str (test_list))

  
# using the naive method
# Separating odd and even index entries

odd_i = []

even_i = []

for i in range ( 0 , len (test_list)):

if i % 2 :

even_i.append (test_list [i])

else :

odd_i.append (test_list [i])

 

res = odd_i + even_i

 
# print result

print ( " Seprated odd and even index list: " + str (res))

Output:

 The original list: [3, 6, 7, 8, 9, 2, 1, 5] Seprated odd and even index list: [3, 7, 9, 1 , 6, 8, 2, 5] 

Method # 2: Using List Slicing

This particular task can be easily accomplished using method of slicing lists in a more compact and efficient way, this is the recommended method for solving this problem.

# Python3 demo code
# Separate odd and even index items
# Use list slicing

 
# initializing list

test_list = [ 3 , 6 , 7 , 8 , 9 , 2 , 1 , 5 ]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Using list slicing
# Separating odd and even index entries

res = test_list [:: 2 ] + test_list [ 1 :: 2 ]

 
# print result

print ( "Seprated odd and even index list:" + str (res))

Output:

 The original list: [3, 6, 7, 8, 9, 2, 1, 5] Seprated odd and even index list: [3, 7, 9, 1, 6, 8, 2, 5] 

Python | Separate odd and even index entries Loops: Questions

Python | Separate odd and even index entries Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method