0

let's assume that there is a list named 'user_ids' as below

>>> len(user_ids)
>>> 742

I want to slice the list by 200 after 742/200 -> 3 times of loop, there going to be a 142 stuffs left with the result, I want it to be in a list again. the result would have the same value with below

sliced_list = [user_ids[0:199],user_ids[200:399],user_ids[400:599],user_uds[600:742]]

I want to make a loop to deal with the user_ids list no matter how many stuffs it has.

I cannot figure out where to start.....any ideas?

Taewoo.Lim
  • 211
  • 3
  • 14

4 Answers4

1

Try this, it will work with any length of user_ids

sliced_list = []
for u in range(0, len(user_ids), 200):
    sliced_list.append(user_ids[u: u + 200])

or with a list comprehension

[user_ids[u: u + 200] for u in range(0, len(user_ids), 200)]
Deepstop
  • 3,627
  • 2
  • 8
  • 21
0

I think this should work but I'm sure there is a prettier way

tempList = []
for i in range(len(user_ids):
    if i % 200 == 0:
        newList.append(tempList)
        tempList = []
    tempList.append(user_ids[i])
lc74
  • 134
  • 8
0

A possible solution:

print([l[200*i:200*(i+1)] for i in range(len(user_ids) // 200)])
olinox14
  • 6,177
  • 2
  • 22
  • 39
0

We can use the range function along with the step value for a clean one liner.

sliced_ids = [user_ids[i:i+200] for i in range(0, len(user_ids), 200)]

If one liner is ugly to the eye, following for loop will do the trick:

sliced_ids = []
slice_length = 200
for i in range(0, len(user_ids), slice_length):
    sliced_ids.append(user_ids[i:i+slice_length])

I prefer the one liner over the second. But not going to judge if one going to use the second approach.

thiruvenkadam
  • 4,170
  • 4
  • 27
  • 26