Tuple in list has less items than the function needs Python 3
I'm kinda new to Programming and Python and I'm self learning before going to uni so please be gentle, I'm a newbie. I hope my english won't have too many grammatical errors.
Basically I had this exercise in a book I'm currently reading to take a list of tuples as a function parameter, then take every item in the each tuple and put it to 2nd power and sum the items up.
My code looks like this and works good if my function call includes the same amount of arguments as the function for loop requires:
def summary(xs): for x,y,z in xs: print( x*x + y*y + z*z) xs =[(2,3,4), (2,-3,4), (1,2,3)] summary(xs)
However, If I use a list with less tuples than the function definition, I get an error: ValueError : not enough values to unpack(expected 3, got 0):
xs =[(2,3,4), (), (1,2,3)]
I would like to know how to make a function that would accept a tuple I shown before () - with no tuples, and the function would return 0. I have been trying multiple ways how to solve this for 2 days already and googling as well, but it occurs to me I'm either missing something or I'm not aware of a function i could use. Thank you all for the help.
One way is to iterate over the tuple values, this would also be the way to tackle this problem in nearly every programming language:
def summary(xs): for item in xs: s = 0 for value in item: s += value**2 print(s)
Or using a list comprehension:
def summary(xs): for item in xs: result = sum([x**2 for x in item]) print(result)
also note that
sum() will return
0 for an empty iterable.
5. Data Structures, Remove the first item from the list whose value is x. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, Tuples may be nested: u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello! Learn how to code in Python. Python 3 List Methods & Functions. Returns the position of the first list item that has a bytes, tuple, list, or range) or
Well, the issue is that you don't have enough indices in your inner tuple to unpack into three variables. The simplest way to go around it is to manually unpack after checking that you have enough variables, i.e.:
def summary(xs): for values in xs: if values and len(values) == 3: x, y, z = values # or don't unpack, refer to them by index, i.e. v, v... print(x*x + y*y + z*z) else: print(0)
Or use a
def summary(xs): for values in xs: try: x, y, z = values # or don't unpack, refer to them by index, i.e. v, v... print(x*x + y*y + z*z) except ValueError: # check for IndexError if not unpacking print(0)
Why no tuple comprehension? - Users, It was only many versions later, in Python 3, that dict and set (24, 'word', 2.5). rather than a long sequence of homogeneous items, like lists, so there is less need for a tuple comprehension. If you need a tuple, use a Do you know what does this function do and what are its performance characteristics? Instead of permanently deleting a tuple, Python moves it to a free list if the tuple has less than 20 items. >>> a = (1,2,3) >>> id(a) 140235617388224 >>> del a >>> b = (4,5,6) >>> id(b)
One way is to use
except. In the below example, we use a generator and catch occasions when unpacking fails with
ValueError and yield 0.
While you are learning, I highly recommend you practice writing functions which
yield rather than using them to
def summary(xs): for item in xs: try: yield sum(i**2 for i in item) except ValueError: yield 0 xs = [(2,3,4), (), (1,2,3)] res = list(summary(xs)) print(res) [29, 0, 14]
Or to actually utilise the generator in a lazy fashion:
for i in summary(xs): print(i) 29 0 14
5. Data Structures, list.remove(x): Remove the first item from the list whose value is x. It is an If the expression would evaluate to a tuple, it must be parenthesized. Here we take a list of numbers and return a list of three times each number: For example, a < b == c tests whether a is less than b and moreover b equals c. When comparing the built-in functions for Python Tuple and the list, Python Tuple has lesser pre-defined built-in functions than the lists. A few of the advantages of lists against the Python Tuple are that the list can be defined for variable lengths and can be copied from one destination to another, but Python Tuple can have only fixed
You should use the "len > 0" condition. This code should work for any list or tuple length :
def summary(xs): for tup in xs: prod = [a*a for a in tup if len(tup)>0] print(sum(prod))
Note that I defined a "prod" list in order to use "sum" so that it is not calculated the hard way. It replaces your "x* x + y* y + z* z" and works for any tuple length.
Optimization tricks in Python: lists and tuples, Python has two similar sequence types such as tuples and lists. a = (1,2,3) >>> a = 10 Traceback (most recent call last): File "<stdin>", line 1, working with arguments and parameters; returning 2 or more items from a function If a tuple no longer needed and has less than 20 items instead of deleting Guido van Rossum, the creator of Python, didn’t like the map() function as it’s less readable (and less efficient) than the list comprehension version (method 1 in this tutorial). You can read about a detailed discussion on how exactly he argued on my blog article.
It often pays to separate your algorithm into functions that just do one thing. In this case a function to sum the squares of a list of values and a function to print them. It is very helpful to keep your variable names meaningful. In this case your
xs is a list of lists, so might be better named
import math def sum_of_squares(xs): return sum(map(math.sqr, xs)) def summary(xss): for xs in xss: print sum_of_squares(xs) xss = [(2,3,4), (), (1,2,3)] summary(xss)
map(print, sum(map(math.sqr, (x for x in xs))))
18 Most Common Python List Questions, Discover how to create a list in Python, select list elements, the difference This is why lists, strings, tuples, and sets are called “iterables”. a certain element is part of your sequence) will go faster with sets than with lists. It's an anonymous function, so you need to pass it your list element to make sure In above code we have tuple a and list b with same items but the size of tuple is less than the list. Different Use Cases At first sight, it might seem that lists can always replace tuples.
Python Tuples Tutorial, Similar to Python lists, tuples are another standard data type that allows you to It is helpful to know some built-in functions with tuples and you will see some Tuples are initialized with () brackets rather than  brackets as with lists. Tuple 'n_tuple' with a list as one of its item. n_tuple = (1, 1, [3,4]) #Items Python has 3 methods for deleting list elements: the item at index 3, from the list, you could use: list can be changed or modified after its creation according to needs whereas tuple has
Lists and Tuples in Python – Real Python, You'll cover the important characteristics of lists and tuples in Python 3. In short, a list is a collection of arbitrary objects, somewhat akin to an array in many other Lists can even contain complex objects, like functions, classes, and modules, which You specify the index of the item to remove, rather than the object itself. A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values.
Tuples, Syntactically, a tuple is a comma-separated list of values: Without the comma Python treats ('a') as an expression with a string in parentheses that Another way to construct a tuple is the built-in function tuple. print t[1:3] ('b', 'c') be checked to see if it is greater than, less than or equal to another value of the same type. Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent