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 Are Ordered Sequences
Lists and Tuples Can Contain Arbitrary Objects
Lists and Tuples Can Be Indexed and Sliced
Lists and Tuples Can Be Nested
Lists Are Mutable, Tuples Are Immutable
Lists Have Mutator Methods, Tuples Don't
|
||||||||||||||||||
Using Operators and Built-in Functions With Lists and Tuples | ||||||||||||||||||
Packing and Unpacking Lists and Tuples | ||||||||||||||||||
Using Lists vs Tuples | ||||||||||||||||||