Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Getting sublist element till N
Next article icon

Python | Get first element of each sublist

Last Updated : 21 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of lists, write a Python program to extract first element of each sublist in the given list of lists. Examples:

Input : [[1, 2], [3, 4, 5], [6, 7, 8, 9]] Output : [1, 3, 6]  Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['x', 'm', 'a', 'u']

  Approach #1 : List comprehension 

Python3




# Python3 program to extract first and last
# element of each sublist in a list of lists
 
def Extract(lst):
    return [item[0] for item in lst]
     
# Driver code
lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
print(Extract(lst))
 
 
Output:
[1, 3, 6]

Time Complexity: O(n)

Space Complexity: O(n) (length of the list given as argument)

  Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the ‘lst’ as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose. 

Python3




# Python3 program to extract first and last
# element of each sublist in a list of lists
 
def Extract(lst):
    return list(list(zip(*lst))[0])
     
# Driver code
lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
print(Extract(lst))
 
 
Output:
[1, 3, 6]

Time Complexity: O(n) (zip function has complexity of O(1) and conversion to list has O(n))

Space Complexity: O(n) (length of the list given as argument)

Another method of using zip is given below:- 

Python3




def Extract(lst):
    return list(next(zip(*lst)))
 
 

  Approach #3 : Using itemgetter() 

Python3




# Python3 program to extract first and last
# element of each sublist in a list of lists
from operator import itemgetter
 
def Extract(lst):
    return list( map(itemgetter(0), lst ))
     
# Driver code
lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
print(Extract(lst))
 
 
Output:
[1, 3, 6]

Time Complexity: O(n) (itemgetter has O(1) and conversion to list O(n))

Space Complexity: O(n)

 Approach #4 : Using reduce

You can use the reduce function from the functools library to iteratively apply a lambda function to the list of lists and build a new list containing the first elements of each sublist.

Python3




from functools import reduce
# Python3 program to extract first and last
# element of each sublist in a list of lists
def extract_first(lst):
    return reduce(lambda acc, x: acc + [x[0]] if x else acc, lst, [])
# Driver code
lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
print(extract_first(lst))
 
 
Output
[1, 3, 6]

Time Complexity: O(n)

Space Complexity: O(n) 

Method#5: using for loop

Approach

this approach uses a for loop to iterate through each sublist and append the first element of each sublist to a new list. The resulting list is returned. 

Algorithm

1. Initialize an empty list to hold the first elements.
2. Iterate through each sublist.
3. For each sublist, append the first element to the list of first elements.
4. Return the list of first elements.

—

Python3




def get_first_element(list_of_lists):
    first_elements = []
    for sublist in list_of_lists:
        first_elements.append(sublist[0])
    return first_elements
 
 
list_of_lists = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
print(get_first_element(list_of_lists))
 
 
Output
[1, 3, 6]

Time complexity: O(n), where n is the number of sublists in the input list. We iterate once over each sublist.

Space complexity: O(n), where n is the number of sublists in the input list. We create a new list to hold the first elements.



Next Article
Python | Getting sublist element till N

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Get last element of each sublist
    Given a list of lists, write a Python program to extract the last element of each sublist in the given list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : [3, 5, 9] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['z', 'm', 'b', 'v'] Approach #1 : List compr
    3 min read
  • Get first element from a List of tuples - Python
    The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of
    2 min read
  • Python | Getting sublist element till N
    Sometimes, we may come across a utility in which we require to get the first N sublist elements that too only a particular index. This can have an application in queuing to get only the initial N person's name. Let's discuss certain ways in which this can be done. Method #1: Using list comprehension
    4 min read
  • Python - First K unique elements
    Sometimes, while working with Python Lists, we can have a problem in which we need to extract first K unique elements. This means we need to extract duplicate if they occur in first K elements as well. This can essentially make count of first K unique elements more than K. This kind of problem can h
    3 min read
  • Sorting List of Lists with First Element of Each Sub-List in Python
    In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list o
    3 min read
  • Get first and last elements of a list in Python
    The task of getting the first and last elements of a list in Python involves retrieving the initial and final values from a given list. For example, given a list [1, 5, 6, 7, 4], the first element is 1 and the last element is 4, resulting in [1, 4]. Using indexingThis is the most straightforward way
    3 min read
  • Python - Substitute K for first occurrence of elements
    Sometimes, while working with Python data, we can have a problem in which, we need to perform a substitution to the first occurrence of each element in list. This type of problem can have application in various domains such as web development. Let's discuss certain ways in which this task can be per
    6 min read
  • Python | List Element Count with Order
    Sometimes, while working with lists or numbers we can have a problem in which we need to attach with each element of list, a number, which is the position of that element's occurrence in that list. This type of problem can come across many domains. Let's discuss a way in which this problem can be so
    4 min read
  • Python - Rows with all List elements
    Given a Matrix, get all the rows with all the list elements. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [1, 2] Output : [[2, 1, 8], [6, 1, 2]] Explanation : Extracted lists have 1 and 2. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [2
    8 min read
  • Python - Check if element is present in tuple
    We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True. Using in Operatorin operator checks if an element is present in a tuple by
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences