61

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?

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
John
  • 1,405
  • 2
  • 14
  • 21

8 Answers8

70

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]
arshajii
  • 127,459
  • 24
  • 238
  • 287
5

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]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

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]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Phil
  • 879
  • 2
  • 10
  • 23
2
List1 = [[10,-13,17],[3,5,1],[13,11,12]]

num = 50
for i in List1[0]:num -= i
print num
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0
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].

Donald Miner
  • 38,889
  • 8
  • 95
  • 118
0
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.

rajpy
  • 2,436
  • 5
  • 29
  • 43
0
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.

Coddy
  • 549
  • 4
  • 18
0
to print every individual element in double list
        list1=[[1,2,3],[4,5,6],[7,8,9]]
        for i in range(len(list1)):
            for j in range(len(list1[i])):
                print(list1[i][j])