Aditya N
Aditya N

Reputation: 3

How to split a list in python based on index

I have a list which has number and description alternatively. I would like to split it into 2 based on the index so that I can separate number and description. I tried this but it doesn't work-

list to be split based on index is named list2

for i in range (0,len(list2),1):
    if (i%2==0):
        new_list1=list() #list only with values
        dummy=list2[i]
        i1=0
        new_list1[i1]=dummy
        i1=i1+2
    else:
        new_lisy2=list() #list with description only
        dummy2=list2[i]
        i2=1
        new_list2[i2]=dummy2
        i2=i2+2

This should work but sadly it doesn't and when I debug it skips going to else statement. Please help.

Upvotes: 0

Views: 113

Answers (1)

smoggers
smoggers

Reputation: 3192

I have a list which has number and description alternatively

Why not just use slicing:

original_list = [1,'one',2,'two',3,'three']
numbers_list = a[::2]    # start at index[0], continue through list, get every 2nd element
>>> print numbers_list
[1, 2, 3]
strings_list = a[1::2]   # start at index[1], continue through list, get every 2nd element
>>> print strings_list
['one', 'two', 'three']

Upvotes: 1

Related Questions