PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to find the product of elements in a multiple tuples in a list

 May 09, 2022     list, list-comprehension, product, python, tuples     No comments   

Issue

I have a list below:

list = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

How do I return a list containing the products of the elements in the tuples, ie.:

[1, 2, 3, 2, 4, 6, 3, 6, 9]

where

1*1 = 1 is the 1st element in the new list

1*2 = 2 is the 2nd element in the new list

1*3 = 3 is the 3rd element in the new list

2*1 = 2 is the 4th element in the new list

2*2 = 4 is the 5th element in the new list

etc.

A way to do this in a list comprehension would be great. Thanks!


Solution

No need to use libraries, a simple list comprehension will do that just fine:

lst = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

products = [a*b for a,b in lst]

# [1, 2, 3, 2, 4, 6, 3, 6, 9]


Answered By - Alain T.
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing