0

I am trying to write a code that picks values in from a list to create to separate lists.

This is my code so far;

list = [6,2,9,10]
for x, y in zip(list, list):
      print (x,y)

Output:

6,2
9,10

But what I want is:

[6,9]
[2,10]
martineau
  • 119,623
  • 25
  • 170
  • 301
Ranaz 116
  • 19
  • 5
  • 3
    Do you want to separate elements located at odd and even indices into two different lists or what are you trying to accomplish? I'm not sure I understand it from your example. – shmulvad Jun 14 '20 at 18:04
  • Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Olvin Roght Jun 14 '20 at 18:06
  • Have edit my code sorry. It could be either way but also want to sum them after but my case does not allow me to sum them. – Ranaz 116 Jun 14 '20 at 18:09
  • `new_lst = [lst[i::2] for i in range(len(lst) // 2)]` – Olvin Roght Jun 14 '20 at 18:09
  • olvin Right your code worked perfectly – Ranaz 116 Jun 14 '20 at 18:16
  • @Ranaz116m do not use `list` or other built-in function names as name of variable. – Olvin Roght Jun 14 '20 at 18:31

2 Answers2

1

You can zip slices of your original list to achieve your goal:

list = [6,2,9,10]
for x, y in zip(list[:2], list[2:]):
      print (x,y)
6 9
2 10

This is not well-generalized - if you had a specific intent like "split my list into a first-half and second-half, and match the elements of those sub-lists" that would be more clear, but hopefully this helps you achieve what you want.

Sam
  • 1,406
  • 1
  • 8
  • 11
0

Assuming you want the elements at even index and odd index split into separate lists, you could do the following.

List1 =[1, 2,3,4,5]
even_list= List1[::2]
Odd_list = List1[1::2]
apoorva kamath
  • 816
  • 1
  • 7
  • 19