Building lists incrementally

Because lists are mutable, you can build them one element at a time. It is often useful to build lists from other iterable objects or to combine multiple lists. The easiest way of doing this is to write a for loop and build the new list with the append() method, as in the following example:

L1 = ['spam'

, 'spam',

'spam', 'baked beans', None,

'spam',

'spam']

L

for i in L1:

if i is not

None:

L2.append(i)

After you run the above code, the value of L2 is ["spam", "spam", "spam", "baked beans", "spam", "spam"] .

After you run the above code, the value of L2 is ["spam", "spam", "spam", "baked beans", "spam", "spam"] .

Warning If you're iterating over a list in a for loop, it's best not to add elements to or delete elements from that list—doing so can introduce errors. It's safer to use code like the above example to build a new list and then change the elements of the new list.

Python provides several other tools for building lists:

• To convert or copy sequences (and other iterable objects) to a list, use the list() function (described earlier in this chapter).

• Another way to copy a whole list or other sequence and return a shallow copy is to use this slice notation: mylist[:]

• Python includes a feature called a list comprehension, which works in much the same way as a list-building for loop but is packaged more compactly. (See Chapter 16 to find out about this advanced feature.)

• To loop over two or more sequences at the same time, use the zip() function. It returns a list of tuples that associates the items in one sequence with the corresponding items in another sequence. It also truncates the resulting list to the length of the shortest sequence.

If you use zip() again with the *args style parameter, you get a list of tuples that correspond to the original sequences you started with (but any items that were truncated are missing).

Tip The *args style argument is explained in Chapter 11. Here's what it could look like:

• To get tuples of list index numbers and their elements, use the enumerate() iterator.

Was this article helpful?

0 0

Post a comment