Normally, there's an ad running in this spot, but you're using an ad blocker. To help support our blog, which provides free tutorials for everybody, we just ask that you whitelist or follow us on facebook, twitter, or subscribe using the form to the leftabove. Thank you!

    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.

    If you're unable to install Python, you also have the option to use the browser-embedded python REPL below. Go ahead and type right inside that code window. To make it more convenient, I recommend that you have two windows of this page running side-by-side. This allows you to run the code in one window, while scrolling through the article in another.


    The Basics

    # creating a list, explicitly
    >>> s = [2, 4, 1, 6, 5, 9]
    # creating a list with a loop
    >>> d = range(0,6)
    >>> d
    [0, 1, 2, 3, 4, 5]
    # appending to a list
    >>> s.append(7)
    >>> s
    [2, 4, 1, 6, 5, 9, 7]
    # retrieving by index
    >>> s[3]
    >>> s[0]

    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)
    >>> l
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    # retrieving the last element of a list
    # with negative indices
    >>> l[-1]
    # 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.

    >>> l1 = ['a', 'b']
    >>> l2 = ['c', 'd']
    >>> l1.extend(l2)
    >>> l1
    ['a', 'b', 'c', 'd']
    >>> l1.append(l2)
    >>> l1
    ['a', 'b', 'c', 'd', ['c', 'd']]
    # combining lists the easy eay
    >>> l1 = ['a', 'b']
    >>> l2 = ['c', 'd']
    >>> l3 = l1 + l2
    >>> l3

    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.

    # create the list
    >>> l = ['a', 'b', 'c']
    # "pop" off the last element
    >>> l.pop()
    # now, only ['a', 'b'] remain in the array
    >>> l
    ['a', 'b']
    # insert 'c' at position 1
    >>> l.insert(1, 'c')
    >>> l
    ['a', 'c', 'b']
    # "pop" off the last element at position 1
    >>> l.pop(1)
    >>> l
    ['a', 'b']
    >>> l.remove(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: list.remove(x): x not in list
    # We have to pass in a value with remove
    >>> l.remove('b')
    >>> l


    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, code>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 (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'tuple' object has no attribute 'append'
    >>> tup.pop()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'tuple' object has no attribute 'pop'
    >>> tup.index("a")
    >>> tup.index("b")


    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
    >>> words = ['The', 'quick', 'brown', 'fox', 'jumped']
    # only return words that contain the letter 'e' 
    >>> [word for word in words if 'e' in word]
    ['The', 'jumped']
    # Make every word uppercase as you go
    >> [word.upper() for word in words if 'e' in word]
    ['THE', 'JUMPED']

    Did you like this tutorial? Help us pay for server costs by following us on Facebook, Twitter, and subscribing below, where you'll get post notifications, training webinar invites, and free bundles.