Access item in a list of lists

PythonList

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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]

Solution 2 - Python

You can use itertools.cycle:

>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0])   # lis[0] is [10,13,17]
36

Here the generator expression inside sum would return something like this:

>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]

You can also use zip here:

>>> cyc = cycle((-1, 1))
>>> [x*y for x, y  in zip(lis[0], cyc)]
[-10, 13, -17]

Solution 3 - Python

This code will print each individual number:

for myList in [[10,13,17],[3,5,1],[13,11,12]]:
    for item in myList:
        print(item)

Or for your specific use case:

((50 - List1[0][0]) + List1[0][1]) - List1[0][2]

Solution 4 - Python

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

num = 50
for i in List1[0]:num -= i
print num

Solution 5 - Python

50 - List1[0][0] + List[0][1] - List[0][2]

List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

Solution 6 - Python

for l in list1:
    val = 50 - l[0] + l[1] - l[2]
    print "val:", val

Loop through list and do operation on the sublist as you wanted.

Solution 7 - Python

new_list = list(zip(*old_list)))

*old_list unpacks old_list into multiple lists and zip picks corresponding nth element from each list and list packs them back.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - PythonarshajiiView Answer on Stackoverflow
Solution 2 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 3 - PythonPhilView Answer on Stackoverflow
Solution 4 - PythonJoran BeasleyView Answer on Stackoverflow
Solution 5 - PythonDonald MinerView Answer on Stackoverflow
Solution 6 - PythonrajpyView Answer on Stackoverflow
Solution 7 - PythonCoddyView Answer on Stackoverflow