3

I have a list that is to be divided into two parts then, each part have to be written into different lists. The code which i tried is here and it works fine.

import sys
a = ['name','2',3,4,5,'a','b','c','d',10,4,'lol','3']
print len(a)
list1 =[]
list2 = []
for i in xrange(0, (len(a)/2)):
    list1.append(a[i])
    list2.append(a[(i)+((len(a)/2))])
list2.append(a[(len(a))-1])
print list1
print list2

I would like to know if there is any other better alternative way to do this..

Sangamesh Hs
  • 1,447
  • 3
  • 24
  • 39

2 Answers2

5

Use Python slice notation:

a = ['name', '2', 3, 4, 5, 'a', 'b', 'c', 'd', 10, 4, 'lol', '3']
n = len(a)
print(n)
mid = n // 2
list1, list2 = a[:mid], a[mid:]
print(list1)
print(list2)
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1
a = ['name','2',3,4,5,'a','b','c','d',10,4,'lol','3']
mid = len(a)//2
list1, list2=a[:mid], a[mid:]


>>> list1
['name', '2', 3, 4, 5, 'a']
>>> list2
['b', 'c', 'd', 10, 4, 'lol', '3']

quite similar to answer 1, but a bit shorter and a bit faster

der_die_das_jojo
  • 893
  • 1
  • 9
  • 21