Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access item in a list of lists

Tags:

python

list

If I have a list of lists and just want to manipulate an individual item in that list, how would I go about doing that?

For example:

List1 = [[10,13,17],[3,5,1],[13,11,12]] 

What if I want to take a value (say 50) and look just at the first sublist in List1, and subtract 10 (the first value), then add 13, then subtract 17?

like image 365
John Avatar asked Aug 26 '13 17:08

John


People also ask

How do I get a list of elements in a list in Python?

We can access the contents of a list using the list index. In a flat list or 1-d list, we can directly access the list elements using the index of the elements. For instance, if we want to use positive values as the index for the list elements, we can access the 1st item of the list using index 0 as shown below.

Can you have a list within a list in Python?

Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.

How do you extract an element from a nested list in Python?

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.

How do I print a list inside a list?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.


Video Answer


1 Answers

You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17 is element 2 in list 0, which is list1[0][2]:

>>> list1 = [[10,13,17],[3,5,1],[13,11,12]] >>> list1[0][2] 17 

So, your example would be

50 - list1[0][0] + list1[0][1] - list1[0][2] 
like image 53
arshajii Avatar answered Oct 02 '22 15:10

arshajii