程式扎記: [Quick Python] 5. Lists, tuples, and sets - Part 2

標籤

2012年1月30日 星期一

[Quick Python] 5. Lists, tuples, and sets - Part 2

Tuples : 
Tuples are data structures that are very similar to lists, but they can’t be modified. They can only be created. Tuples are so much like lists that you may wonder why Python bothers to include them. The reason is that tuples have important roles that can’t be efficiently filled by lists, as keys for dictionaries. 

- Tuple basics 
Creating a tuple is similar to creating a list: assign a sequence of values to a variable. A list is a sequence that is enclosed by [ and ]; a tuple is a sequence that is enclosed by ( and ). For example : 
>>> x = ('a', 'b', 'c') # This line creates a three-element tuple.

After a tuple is created, using it is so much like using a list that it’s easy to forget they’re different data types : 
 

The main difference between tuples and lists is that tuples are immutable. An attempt to modify a tuple results in a confusing error message, which is Python’s way of saying it doesn’t know how to set an item in a tuple : 
>>> x[2] = 'd'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment

You can create tuples from existing ones by using the + and * operators : 
>>> x + x
('a', 'b', 'c', 'a', 'b', 'c')
>>> x * 2
('a', 'b', 'c', 'a', 'b', 'c')

A copy of a tuple can be made in any of the same ways as for lists : 
>>> x[:]
('a', 'b', 'c')
>>> x * 1
('a', 'b', 'c')
>>> x + ()
('a', 'b', 'c')

Tuples themselves can’t be modified. But if they contain any mutable objects (for example, lists or dictionaries), these may be changed if they’re still assigned to their own variables. Tuples that contain mutable objects aren’t allowed as keys for dictionaries. 

- One-element tuples need a comma 
A small syntactical point is associated with using tuples. Because the square brackets used to enclose a list aren’t used elsewhere in Python, it’s clear that [] means an empty list and [1] means a list with one element. The same thing isn’t true with the parentheses used to enclose tuples. Parentheses can also be used to group items in expressions in order to force a certain evaluation order. If we say (x + y) in a Python program, do we mean that x and y should be added and then put into a one-element tuple, or do we mean that the parentheses should be used to force x and y to be added, before any expressions to either side come into play

This is only a problem for tuples with one element, because tuples with more than one element always include commas to separate the elements, and the commas tell Python the parentheses indicate a tuple, not a grouping. In the case of one-element tuples, Python requires that the element in the tuple be followed by a comma, to disambiguate the situation. In the case of zero-element (empty) tuples, there’s no problem. An empty set of parentheses must be a tuple, because it’s meaningless otherwise : 
 

- Packing and unpacking tuples 
As a convenience, Python permits tuples to appear on the left-hand side of an assignment operator, in which case variables in the tuple receive the corresponding values from the tuple on the right-hand side of the assignment operator. Here’s a simple example : 
>>> (one, two, three, four) = (1, 2, 3, 4)
>>> one
1
>>> two
2

This can be written even more simply, because Python recognizes tuples in an assignment context even without the enclosing parentheses. The values on the right-hand side are packed into a tuple and then unpacked into the variables on the left-hand side : 
>>> one, two, three, four = 1, 2, 3, 4

This is a convenient way to swap values between variables. Instead of saying : 
temp = var1
var1 = var2
var2 = temp

just say : 
var1, var2 = var2, var1

To make things even more convenient, Python 3 has an extended unpacking feature, allowing an element marked with a * to absorb any number elements not matching the other elements. Again, some examples will make this clearer : 
 

Note that the starred element receives all the surplus items as a list, and that if there are no surplus elements, it receives an empty list. Packing and unpacking can be performed using list delimiters as well : 
 

- Converting between lists and tuples 
Tuples can be easily converted to lists with the list() function (which takes any sequence as an argument and produces a new list with the same elements as the original sequence). Similarly, lists can be converted to tuples with the tuple() function (which does the same thing but produces a new tuple instead of a new list) : 
>>> list((1, 2, 3, 4))
[1, 2, 3, 4]
>>> tuple([1, 2, 3, 4])
(1, 2, 3, 4)

As an interesting side note, list() is a convenient way to break a string into characters : 
>>> list("Hello")
['H', 'e', 'l', 'l', 'o']

This works because list() (and tuple()) apply to any Python sequence, and a string is just a sequence of characters. 

Sets : 
set in Python is an unordered collection of objects used in situations where membership and uniqueness in the set are main things you need to know about that object. Just as with dictionary keys, the items in a set must be immutable and hashable. This means that ints, floats, strings, and tuples can be members of a set, but lists, dictionaries, and sets themselves can’t. 

- Set operations 
In addition to the operations that apply to collections in general, like inlen, and being able to use a for loop to iterate over all of their elements, sets also have several set-specific operations : 
 

You can create a set by using set on a sequence, like a list (1). When a sequence is made into a set, duplicates are removed (2). After creating a set using the set function, you can use add (3) and remove (4) to change the elements in the set. The in keyword is used to check for membership of an object in a set (5). You can also use | (6) to get the union, or combination, of two sets, & to get their intersection (7), and ^ (8) tofind their symmetric difference—that is, elements that are in one set or the other but not both. 

These examples aren’t a complete listing of set operations but are enough to give you a good idea of how sets work. For more information, refer to the official Python documentation. 

- Frozensets 
Because sets aren’t immutable and hashable, they can’t belong to other sets. To remedy that situation there is another set type, frozenset (by built-in frozenset()), which is just like a set but can’t be changed after creation. Because frozensets are immutable and hashable, they can be members of other sets : 
 

Supplement : 
[Python 學習筆記] 起步走 : 內建型態與操作 (Tuple) 
[Python 學習筆記] 起步走 : 內建型態與操作 (集合)

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!