Python Forum
Take first Elements of sublists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Take first Elements of sublists
#1
This is my list:

list_of_lists = [[1, 2], [3, 4]]
I want to group of elements of sublists:

list_of_lists = [[1, 2], [3, 4]]
n=[]
for list in list_of_lists:
   n.append(list[0]) #I am taking 1 and 3
   n.append(list[1]) # I am taking 2 and 4 
But sometimes I can have 100 elements too so I want to do it dynamically instead of writing [0],[1]

How can I do that?
Reply
#2
Have a look at built-in zip
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
list_of_lists = [[1, 2], [3, 4]]
print(list(zip(*list_of_lists)))
Output:
[(1, 3), (2, 4)]
quest likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List of lists - merge sublists with common elements medatib531 1 1,172 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Sorting Elements via parameters pointing to those elements. rpalmer 3 979 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  Flatten list sublists chesschaser 8 1,291 Jul-07-2020, 11:38 AM
Last Post: chesschaser
  Converting list elements and sublists from int to str iMuny 5 2,887 Mar-10-2019, 09:05 PM
Last Post: iMuny

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020