User Tools

Site Tools


python3_unpacking

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
python3_unpacking [2018/08/06 10:11]
jguerin
— (current)
Line 1: Line 1:
-====== Unpacking Sequences ====== 
- 
-Sequences can be explicitly/implicitly //unpacked// into discrete, ordered units of some type. Unpacking happens automatically using the '','' (comma). (The syntax is also used for [[python3_tuples|Tuple]] construction.) 
- 
-Unpacking works //only// in instances where the number of variables used //exactly// matches the number of items in the sequence. 
- 
-In the below examples parenthesis are not required, and are included for clarity. 
- 
-=====Implicit Unpacking: Member Assignment===== 
-The most common application of unpacking is to (shallow) copy items into named variables. 
- 
-====Lists==== 
-Unpacking a [[python3_lists|List]]. 
-<code python> 
->>> seq = [1, 2, 3] 
->>> (a, b, c) = seq  # a=1, b=2, c=3 
-</code> 
- 
-====Tuples==== 
-Unpacking a [[python3_tuples|Tuple]]. 
-<code python> 
->>> tup = ('a', 'b') 
->>> (x, y) = tup # x='a', y='b' 
-</code> 
- 
-====Strings==== 
-Unpacking the characters of a [[python3_strings|String]]. 
-<code python> 
->>> (fst, snd, thd) = "abc" # fst='a', snd='b', thd='c' 
-</code> 
- 
-=====In-Place Swap/Mutual Replacement===== 
-Swapping objects. 
-<code python> 
->>> x = 1 
->>> y = 2 
->>> (x, y) = (y, x) # x=2, y=1 
-</code> 
- 
- 
-=====Explicit Unpacking: The * (Star) Operator===== 
-The unary ''*'' (star) operator is used to explicitly indicate unpacking, often outside the context of assignment. 
- 
-This is commonly used when elements of a sequence are intended to be used as the parameters to a function. 
- 
-E.g., (Assume that ''seq'' contains 3 elements) ''fun(seq[0], seq[1], seq[2])'' could be rephrased more tersely as ''fun(*seq)''. 
- 
-====Unpacking Arguments==== 
-<code python> 
->>> print([1, 2, 3]) # legal, but performs a cast str([1, 2, 3]) 
-[1, 2, 3] 
-</code> 
- 
-<code python> 
->>> print(*[1, 2, 3]) # as though we indexed each individually 
-1 2 3 
-</code> 
- 
-<code python> 
-</code> 
- 
-====Extended Iterable Unpacking==== 
- 
  
python3_unpacking.1533568267.txt.gz ยท Last modified: 2018/08/06 10:11 by jguerin