0

I have a data structure like this

[[1,2,3,4,5], {9,2,5,8,7}, (7, 4, 8, 6)]

One big list containing lists, sets, and tuples.

I want to multiply everything inside a list by 3, but not the things inside tuple or set. Output should be:

[[3,6,9,12,15], {9,2,5,8,7}, (7, 4, 8, 6)]

The items inside the list all got multiplied by 3, rest remain unchanged.

I have tried this:

l = [[2,6,9,13,15], {9,2,5,8,7}, (7, 4, 8, 6)]
newList = [[subitem*3 for subitem in subList ] for subList in l]
print(newList)

But this gives me bad output:

[[3, 6, 9, 12, 15], [24, 27, 6, 15, 21], [21, 12, 24, 18]]   

The list is good, but the set and tuple need to remain unchanged, they shouldn't be converted to list either. I want output exactly like I have shown previously.

Thanks!

3 Answers3

1

You can use this comprehension pattern: [x if a else b for x in lst]:

new_list = [[3*y for y in x] if isinstance(x, list) else x for x in l]

Look here for more discussion.

Community
  • 1
  • 1
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks for the answer, I didn't realize the solution was this simple. Apologies. I'll accept this one since it was posted first. (can't accept yet, have to wait 5 minutes) – user89239213892389 Jun 06 '16 at 14:34
1

The code you provided was so close, all you need to do is add a check for if the subList is a list, then if so multiply else leave alone.

l = [[2,6,9,13,15], {9,2,5,8,7}, (7, 4, 8, 6)]
newList = [[subitem*3 for subitem in subList ] if type(subList) is list else subList for subList in l]
print(newList)
Copy and Paste
  • 496
  • 6
  • 16
1
newList = [[subitem*3 for subitem in subList ] if isinstance(subList, list) else subList for subList in l]

This can be an option!

SeF
  • 3,864
  • 2
  • 28
  • 41