0
w = ['a','b','c','d','e','f','g','h']   
l = []

a = w[0:2]
b = w[2:4]
c = w[4:6]
d = w[6:8]


l = [a,b,c,d]              #[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

How can i get the same result ('w' to 'l') using loop method instead of slicing multiple times? Assuming i dont know how many characters can there be in 'w' variable (in this example it is just from 'a' to 'h'), and slicing will always start from 0 but the range in unknown(where in this example it is 0:2)

Thank You very much.

mikal
  • 55
  • 6

1 Answers1

0

You can use the range function with list comprehension

w = ['a','b','c','d','e','f','g','h']   
length = 2
step = 2
l = [w[i:i + length] for i in range(0,len(w),step)]
l
#[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
ExplodingGayFish
  • 2,807
  • 1
  • 5
  • 14