54

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
  • 19,240
  • 7
  • 48
  • 73
John
  • 1,325
  • 2
  • 11
  • 21

7 Answers7

66

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
  • 123,543
  • 24
  • 232
  • 276
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
  • 232,417
  • 55
  • 437
  • 487
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
  • 232,417
  • 55
  • 437
  • 487
Phil
  • 857
  • 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
  • 103,130
  • 11
  • 146
  • 174
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
  • 37,251
  • 7
  • 89
  • 116
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,336
  • 4
  • 27
  • 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
  • 467
  • 3
  • 14