Python unpack list in list comprehension

list() vs iterable unpacking in Python 3.5+

Is there any practical difference between list(iterable) and [*iterable] in versions of Python that support the latter?

Corner case: it’s possible to rebind the name list to something other than the built-in type, but you can’t change the meaning of the [*iterable] syntax.

5 Answers 5

list(x) is a function, [*x] is an expression. You can reassign list , and make it do something else (but you shouldn’t).

Talking about cPython, b = list(a) translates to this sequence of bytecodes:

LOAD_NAME 1 (list) LOAD_NAME 0 (a) CALL_FUNCTION 1 STORE_NAME 2 (b) 
LOAD_NAME 0 (a) BUILD_LIST_UNPACK 1 STORE_NAME 3 (c) 

so you can argue that [*a] might be slightly more efficient, but marginally so.

You can use the standard library module dis to investigate the byte code generated by a function. In this case:

import dis def call_list(x): return list(x) def unpacking(x): return [*x] dis.dis(call_list) # 2 0 LOAD_GLOBAL 0 (list) # 2 LOAD_FAST 0 (x) # 4 CALL_FUNCTION 1 # 6 RETURN_VALUE dis.dis(unpacking) # 2 0 LOAD_FAST 0 (x) # 2 BUILD_LIST_UNPACK 1 # 4 RETURN_VALUE 

So there is a difference and it is not only the loading of the globally defined name list , which does not need to happen with the unpacking. So it boils down to how the built-in list function is defined and what exactly BUILD_LIST_UNPACK does.

Note that both are actually a lot less code than writing a standard list comprehension for this:

def list_comp(x): return [a for a in x] dis.dis(list_comp) # 2 0 LOAD_CONST 1 ( ) # 2 LOAD_CONST 2 ('list_comp..') # 4 MAKE_FUNCTION 0 # 6 LOAD_FAST 0 (x) # 8 GET_ITER # 10 CALL_FUNCTION 1 # 12 RETURN_VALUE 

Источник

Python Tuple Unpacking with Examples

In Python, Tuple unpacking is a feature that allows us to assign values to multiple variables in a single statement. It works by unpacking a sequence (e.g., a tuple, list, or string) into individual variables. Unpacking is not limited to tuples, you can also use it to unpack lists, strings, and other iterable objects. Unpacking is a powerful feature in Python that can make your code more concise and readable.

You can unpack tuples in python by using many ways, for example, using the * unpacking, dictionary , lambda , and list comprehension . In this article, I will explain tuple unpacking by using all these methods with examples.

1. Quick Examples of Tuple Unpacking

If you are in a hurry, below are some quick examples of python tuple unpacking.

 # Quick examples of tuple unpacking # Example 1: Using * unpacking method tuples = ('Spark', 'Python', 'pandas', 'Java') list1 = [*tuples,] # Example 2: Unpacking tuples as arguments def technology(courses, fees, duration): print(courses) print(fees) print(duration) tuples = ('Python', 25000, '50days') technology(*tuples) # Example 3: Unpacking tuples as a dictionary tuples = ('Python', '50days', 25000) dictionary = dict(zip(('courses', 'duration', 'fees'), tuples)) # Example 4: Unpacking tuples as a dictionary object tuples = ('Python', '50days', 25000) dictionary = <> dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples # Example 5: Unpacking tuples using lambda function tuples = (5, 10) result = (lambda x,y: x + y)(*tuples) # Example 6: Unpacking nested tuples # Using list comprehension nested_tuple = ((2, 4), (6, 8), (10, 12)) result = [x + y for x, y in nested_tuple] # Example 7: Using list comprehension tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17)) result = [(x,y,z) for x,y,z in tuples] 

2. Using * Unpacking Method

You can use unpack operator * on a tuple to extract the individual elements from a tuple and assign its elements to a list by enclosing the tuple in square brackets [] and separating the elements with commas . For example, use the * operator to unpack the elements of the tuples and assign them to the list list1 . The resulting list contains the same elements as the original tuple, in the same order.

 # Using * unpacking method tuples = ('Spark', 'Python', 'pandas', 'Java') # convert tuple into list list1 = [*tuples,] print(list1) # Output # ['Spark', 'Python', 'pandas', 'Java'] 

3. Unpacking Tuple as Arguments

You can unpack tuple and pass the elements of a tuple as arguments to a function in Python. This is a convenient way to pass multiple arguments to a function without having to manually specify each argument.

For example, In the below code snippet we define a function technology that takes three arguments courses , fees , and duration . And, create a tuple tuples with three elements and use tuple unpacking with the * operator to pass the elements of the tuple as arguments to the function.

 # Unpacking tuple as arguments def technology(courses, fees, duration): print(courses) print(fees) print(duration) tuples = ('Python', 25000, '50days') technology(*tuples) # Output # Python # 25000 # 50days 

4. Unpacking Tuples as Dictionary

To unpack a tuple as a dictionary, you can use the dict() constructor along with the zip() function to create a dictionary from the key-value pairs generated by the zip() function.

For example, let’s take tuple with three elements, and create a dictionary dictionary with keys courses , fees , and duration corresponding to the elements of the tuple. First, use the zip() function to create a sequence of key-value pairs by matching each element of the tuple with a corresponding key. Then, you use the dict() constructor to convert the sequence of key-value pairs into a dictionary.

 # Unpacking tuples as dictionary tuples = ('Python', '50days', 25000) dictionary = dict(zip(('courses', 'duration', 'fees'), tuples)) print(dictionary) # Output #

Follow the other example of unpacking a tuple as a dictionary object.

 # Unpacking tuples as dictionary object tuples = ('Python', '50days', 25000) dictionary = <> dictionary['courses'],dictionary['duration'],dictionary['fees'] = tuples print(dictionary) # Output #

5. Unpacking Tuples Using Lambda Function

You can also use a lambda function to unpack tuples in Python. For example, you define a lambda function that takes two arguments x and y , and returns their sum. Use the * operator to unpack the tuple and pass their contents as arguments to the lambda function. The result is the sum of the two values in the tuple, which is 15 .

 # Unpacking tuples using lambda function tuples = (5, 10) result = (lambda x,y: x + y)(*tuples) print(result) # Output # 15 

6. Unpacking Nested Tuples Using List Comprehension

You can also use list comprehension to unpack nested tuples in Python. For example, create a nested tuple with three tuples, each containing two values. You can use a list comprehension to iterate over each tuple in the nested_tuple , unpack the values using the syntax x , and y , and add them together to create a new list with the resulting values.

 # Unpacking nested tuples # Using list comprehension nested_tuple = ((2, 4), (6, 8), (10, 12)) result = [x + y for x, y in nested_tuple] print(result) # Output # [6, 14, 22] 

Follow the other example of a list comprehension to unpack nested tuples in Python.

 # Unpacking nested tuples # Using list comprehension tuples = ((1, 3, 5), (7, 9, 11), (13, 15, 17)) result = [(x,y,z) for x,y,z in tuples] print(result) # Output # [(1, 3, 5), (7, 9, 11), (13, 15, 17)] 

Conclusion

In this article, I have explained python tuple unpacking by using * unpacking, dictionary , lambda , and list comprehension with examples.

References

You may also like reading:

Источник

python: unpacking the lists and sets

enter image description here

but it causes problem TypeError: expected string or buffer and, yes, I've looked through other similar questions. Please tell me how to do it correctly and regex chooses accurately what I need

1 Answer 1

You can not apply a regular expression to a list. You could turn the list into a string using str , and then apply the regex, but you probably should not. *)

Intead, I suggest a recursive function for flattening the list, and also iterating both the keys and values in any nested dictionaries, and applying itself recursively to any nested lists, sets, tuples or dicts.

def unpack(seq): if isinstance(seq, (list, tuple, set)): yield from (x for y in seq for x in unpack(y)) elif isinstance(seq, dict): yield from (x for item in seq.items() for y in item for x in unpack(y)) else: yield seq lst = [None, [1, (, )]] print(list(unpack(lst))) # [None, 1, 2, 3, 'foo', 'bar'] 

Update: For Python 2.x, replace the yield from (. ) with for x in (. ): yield x , or directly return lists instead of using a generator to yield elements:

def unpack(seq): if isinstance(seq, (list, tuple, set)): return [x for y in seq for x in unpack(y)] elif isinstance(seq, dict): return [x for item in seq.items() for y in item for x in unpack(y)] else: return [seq] 

*) Since you asked: what if the numbers contain a dot, or the strings contain. well, anything? Also, you'd have to recreate the actual objects with their proper type (like int ) from the matched strings. And what if the list contains objects other than strings or numbers, that can not easily be recreated from their string representation?

Источник

How to Unpack a List in Python

Summary: in this tutorial, you’ll learn how to unpack a list in Python to make your code more concise.

Introduction to the list unpacking

The following example defines a list of strings:

colors = ['red', 'blue', 'green']Code language: Python (python)

To assign the first, second, and third elements of the list to variables, you may assign individual elements to variables like this:

red = colors[0] blue = colors[1] green = colors[2] Code language: Python (python)

However, Python provides a better way to do this. It’s called sequence unpacking.

Basically, you can assign elements of a list (and also a tuple) to multiple variables. For example:

red, blue, green = colorsCode language: Python (python)

This statement assigns the first, second, and third elements of the colors list to the red , blue , and green variables.

In this example, the number of variables on the left side is the same as the number of elements in the list on the right side.

If you use a fewer number of variables on the left side, you’ll get an error. For example:

colors = ['red', 'blue', 'green'] red, blue = colors Code language: Python (python)
ValueError: too many values to unpack (expected 2)Code language: Python (python)

In this case, Python could not unpack three elements to two variables.

Unpacking and packing

If you want to unpack the first few elements of a list and don’t care about the other elements, you can:

  • First, unpack the needed elements to variables.
  • Second, pack the leftover elements into a new list and assign it to another variable.

By putting the asterisk ( * ) in front of a variable name, you’ll pack the leftover elements into a list and assign them to a variable. For example:

colors = ['red', 'blue', 'green'] red, blue, *other = colors print(red) print(blue) print(other) Code language: Python (python)
red blue ['green']Code language: Python (python)

This example assigns the first and second elements of the colors list to the red and green variables. And it assigns the last element of the list to the other variable.

colors = ['cyan', 'magenta', 'yellow', 'black'] cyan, magenta, *other = colors print(cyan) print(magenta) print(other) Code language: Python (python)
cyan magenta ['yellow', 'black']Code language: Python (python)

This example assigns the first and second elements to variables. It packs the last two elements in a new list and assigns the new list to the other variable.

Summary

  • Unpacking assigns elements of the list to multiple variables.
  • Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.

Источник

Читайте также:  Форма ввода в HTML5
Оцените статью