Access only first element in each sub-list

share link

by vigneshchennai74 dot icon Updated: Mar 3, 2023

technology logo
technology logo

Guide Kit Guide Kit  

Extracting the first item of each sublist can be useful in various situations, especially when working with lists of tuples or lists of lists. Here are some examples: 

  • Extracting column data from a table: Suppose you have a table represented as a list of lists, where each inner list represents a row of data. When you want to extract data from a specific table column, you can use a list comprehension to extract the first element of each row (which corresponds to the first column). 
  • Accessing attributes of objects in a list: Suppose you have a list of objects, and each object has several attributes stored as a tuple or a list. Suppose you want to access a specific attribute of each object. In that case, you can use a list comprehension to extract the first element of each tuple or list (which corresponds to the attribute you are interested in). 
  • Creating a dictionary from a list of tuples: If you have a list of tuples where the first element of each tuple is a key and the second element is a value. When you want to create a dictionary from this list, you can use dictionary comprehension to create a dictionary where the keys are the first elements of the tuples. 


For is a control flow statement in Python that is used to iterate over a sequence (such as a list, tuple, string, or dictionary) or another iterable object Here is an example of how to access only the first element in each sub-list: 

Preview of the output that you will get on running this code.

Code

In this solution we have used for loop of python.

  1. Copy this code using "Copy" button above and paste it in your Python ide
  2. Run the code, Access only first element in each sub-list


I hope you have found this useful. I have added the version information in the following section.


I found this code snippet by searching "Python: Access multi-dimensional list" in kandi. you can try any use case.

Environment Tested

In this solution we have used the following versions. Be mindful to change when working with other versions.


  • This solution is created using Python version 3.7.15


Using this solution we can able to Access the first element in each sub-list in python with simple Steps. This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help us to access the first element in sub-list in Python.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.