Getting Started With Lists and Tuples | ||||||||||||||||||
a list is a collection of arbitrary objects to define a list typically enclose a comma-separated sequence of objects in square brackets ([]) >>> colors = ["red", "green", "blue", "yellow"] >>> colors ['red', 'green', 'blue', 'yellow']tuples are also collections of arbitrary objects to define a tuple enclose a comma-separated sequence of objects in parentheses (()) >>> person = ("Jane Doe", 25, "Python Developer", "Canada") >>> person ('Jane Doe', 25, 'Python Developer', 'Canada')lists and tuples are mostly the same
Creating Lists in Python
different ways to create lists
# using a literal >>> countries = ["United States", "Canada", "Poland", "Germany", "Austria"] >>> countries ['United States', 'Canada', 'Poland', 'Germany', 'Austria'] # using the c'tor' >>> digits = list(range(10)) >>> digits [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # using a list comprehension >>> even_digits = [number for number in range(1, 10) if number % 2 == 0] >>> even_digits [2, 4, 6, 8] # create an empty list - two ways >>> [] [] >>> list() [] Creating Tuples in Python
simple tuple creation containing db information
>>> connection = ("localhost", "8080", 3, "database.db") >>> connection ('localhost', '8080', 3, 'database.db')parentheses are not required but increase readability >>> contact = "John Doe", "[email protected]", "55-555-5555" >>> contact ('John Doe', '[email protected]', '55-555-5555')because parentheses are optional when creating a single item tuple a comma is required >>> t = (2,) >>> type(t) <class 'tuple'> >>> t = (2) >>> type(t) <class 'int'>using the tuple c'tor >>> tuple(range(10)) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
||||||||||||||||||
Core Features of Lists and Tuples | ||||||||||||||||||
Lists and Tuples Can Contain Arbitrary Objects
lists and tuples can contain any Python objectssince everything in Python is an object even functions can be included in a tuple both can contain duplicate elements Lists and Tuples Can Be Indexed and Sliced
both use zero-based indexesboth can be sliced using the [:] operator Lists and Tuples Can Be Nested
below the first, third and fifth elements of the list the second element is a list which contains a list as its second element the fourth element is also a list x = ["a", ["bb", ["ccc", "ddd"], "ee", "ff"], "g", ["hh", "ii"], "j"]to access the second element of the list y = x[1]to access the second element of y z = y[1] # or z = x[1][1] Lists Are Mutable, Tuples Are Immutable
lists can be modified while tuples can'tmodify list using an index >>> letters = ["A", "B", "c", "d"] # A list >>> letters[2] = "C" >>> letters ['A', 'B', 'C', 'd'] >>> letters[-1] = "D" >>> letters ['A', 'B', 'C', 'D']can use the del statement to remove a list element >>> fruits = ["apple", "orange", "mango", "grape"] >>> del fruits[0] # Remove apple >>> fruits ['orange', 'mango', 'grape']can change multiple elements at once using a slice assignment >>> numbers = [1, 2, 3, 0, 0, 0, 7] >>> numbers[3:6] = [4, 5, 6] >>> numbers [1, 2, 3, 4, 5, 6, 7]list can grow or shrink as needed >>> numbers = [1, 2, 3, 7] >>> numbers[3:4] = [4, 5, 6, 7] >>> numbers [1, 2, 3, 4, 5, 6, 7] Lists Have Mutator Methods, Tuples Don't
lists have several methods which can be used to modify the underlying listthe .append(obj) method appends an object to the end of a list as a single item >>> a = ["a", "b"] >>> a.append("c") >>> a ['a', 'b', 'c']if an iterable is the .append() argument the iterable is appended as a single object >>> a = ["a", "b"] >>> a.append(["c", "d", "e"]) >>> a ['a', 'b', ['c', 'd', 'e']]the .extend() method also adds items to the end of a list the .extend() argument is expected to be an iterable the items in the input iterable are added as individual values >>> a = ["a", "b"] >>> a.extend(["c", "d", "e"]) >>> a ['a', 'b', 'c', 'd', 'e']the .insert() method inserts the object into the target list at the position specified by index .insert(index, obj)a[<index>] is <obj> the remaining list elements are pushed to the right >>> a = ["a", "c"] >>> a.insert(1, "b") >>> a ['a', 'b', 'c']the .remove() method removes the input object from a list if obj isn't in the list, a ValueError exception is raised >>> a = ["a", "b", "c", "d", "e"] >>> a.remove("b")>>> a ['a', 'c', 'd', 'e']the .pop() method can remove items from a list .pop([index=-1])differs from .remove()
>>> a = ["a", "b", "c", "d", "e"] >>> a.pop() 'e' >>> a ['a', 'b', 'c', 'd'] >>> a.pop() 'd' >>> a ['a', 'b', 'c']if the optional index argument is specified, then the item at that index is removed and returned the index can be negative >>> a = ["a", "b", "c", "d", "e"] >>> a.pop(1) 'b' >>> a ['a', 'c', 'd', 'e'] >>> a.pop(3) 'e' >>> a ['a', 'c', 'd'] >>> a.pop(-2) 'c' >>> a ['a', 'd'] >>> a.pop(-1) 'd' >>> a ['a'] |
||||||||||||||||||
Using Operators and Built-in Functions With Lists and Tuples | ||||||||||||||||||
can run membership tests on both using in and not in operators concatenation (+) and repetition (*) operators work with both can also use the built-in len(), min(), max(), and sum() functions with lists and tuples |
||||||||||||||||||
Packing and Unpacking Lists and Tuples | ||||||||||||||||||
packing a tuple
>>> t = ("foo", "bar", "baz", "qux")unpacking the tuple above >>> s1, s2, s3, s4 = t >>> s1 'foo' >>> s2 'bar' >>> s3 'baz' >>> s4 'qux'when unpacking a tuple, the number of variables on the left must match the number of values in the tuple >>> s1, s2, s3 = t Traceback (most recent call last): ... ValueError: too many values to unpack (expected 3) >>> s1, s2, s3, s4, s5 = t Traceback (most recent call last): ... ValueError: not enough values to unpack (expected 5, got 4) |
||||||||||||||||||
Using Lists vs Tuples | ||||||||||||||||||
appropriate to use a list
|