Sunday, November 30, 2014

Lists, Tuples, and Slicing in Python 2.7

In this guide, we're focusing more on some of the intermediate list capabilities of Python. If you already have a basic understanding of lists, you should already be familiar with tasks like list creation, appending, retrieving by index, and so on. We'll start by recapping on those and then move on to more advanced concepts.

Lists

The Basics

# creating a list dynamically
d = range(0,6)
# [0, 1, 2, 3, 4, 5]

# creating a list, statically
s = [2, 4, 1, 6, 5, 9]

# appending to a list
s.append(7)
# [2, 4, 1, 6, 5, 9, 7]

# retrieving by index
s[3] # 6
s[0] # 2

Negative Indices, Slicing and Strides

Did you know you could retrieve elements working down from the end of the list, as well? What about retrieving ranges of values? What about slicing out values into a new list? Read on to learn more.

l = range(0,10)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# retrieving the last element of a list
# with negative indices
l[-1] # 9

# slicing out a range of elements
l[2:6] # [2, 3, 4, 5]

# not indicating a start index
# ...defaults to 0
l[:6] # [0, 1, 2, 3, 4, 5]

# providing a stride of 2
# ...will increment by 2 instead of 1
l[:6:2] # [0, 2, 4]

Append vs. Extend

extend ends up being the better tool for merging lists together, since append inserts values as if they were the next element of the list.

# extend vs. append
l1 = ['a', 'b']
l2 = ['c', 'c']

l1.extend(l2) # ['a', 'b', 'c', 'd']

li.append(l2) # ['a', 'b', ['c', 'd']]

Pop vs. Remove

Use pop when you want to delete an element by index and remove when you want to delete an element by value.

l = ['a', 'b', 'c']

l.pop() # ['a', 'b']

l.insert(1, 'c') # ['a', 'c', 'b']

l.pop(1) # ['a', 'b']

l.remove(1) #throws error

# have to pass in a value with remove
l.remove('b') # ['a']

Tuples

Tuples are very similar to lists, but they're immutable. Once defined, you can't change the values, add to, or remove from a tuple. Tuples also have no methods associated with modifying them. You can't use use append, pop, or index. However, you can use in. Also, Tuples are heterogeneous data structures. In other words, their entries have different meanings, where lists are homogeneous. You create tuples with parenthesis, rather than square brackets. Check out the examples below.

# create tuple
tup = ('a', 'b', 'c', 'd', 'e')

tup.append("new")
# Traceback (innermost last):
#   File "", line 2, in ?
# AttributeError: 'tuple' object has no attribute 'append'

tup.pop()
# Traceback (innermost last):
#   File "", line 2, in ?
# AttributeError: 'tuple' object has no attribute 'pop'

tup.index("a")
# Traceback (innermost last):
#   File "", line 2, in ?
# AttributeError: 'tuple' object has no attribute 'index'

"a" in tup # True

Similarities

The similarities include a defined order, zero-based indices, negative indices, and the ability to slice.

Advantages Over Lists

  • Tuples perform better than lists. Always use tuples when working with constant values you just need to iterate over.
  • Tuples require less memory than lists. Because you can append to lists, Python will actually create a larger allocation for lists in memory in case you append.
  • Tuples can be used as dictionary keys because dictionaries don't have to worry about them changing, while a list cannot.
# Tuple with 2 numbers
tup = (1, 2)

# Create a dictionary with the tuple as the key
dict = {}
dict[tup] = "Hello World!"

# Access the dictionary using a tuple.
print(dict[(1, 2)]) # "Hello World!"

List Comprehensions

Think of list comprehensions as a shorthand way of writing loops.

Performing Mathematical Operations on Every Element

# list comprehensions

l = [1, 2, 3, 4]

# multiply every element by 2 
[x * 2 for x in l] # [2, 4, 6, 8]

# ...or square the values
[x * x for x in l] # [1, 4, 9, 16]

Filtering Elements

# list comprehensions

l = ['Now', 'I', 'am', 'become', 'death', 'the', 'destroyer', 'of', 'worlds']

# only return words that contain the letter 'e' 
[word for word in words if 'e' in word]
# ['become', 'death', 'the', 'destroyer']

# go even further and make every word uppercase as you go
[word.upper() for word in words if 'e' in word]
# ['BECOME', 'DEATH', 'THE', 'DESTROYER']

3 comments:

  1. Tuples do not have many methods. I found two (count and index) by opening my python3 interpreter an running "dir(tuple)"

    ReplyDelete
    Replies
    1. Side note: Have you thought about blogging about python's arrays (http://pymotw.com/2/array/)?

      Delete
    2. Much appreciated. Updated the article. Also, will include a section on arrays, soon.

      Delete