Python basics - briefly. Part 3. Lists, tuples, files.

    In general, the last of the finished chapters. The rest will come out a little less often, because they have not been written yet (but I'm sure they will, although it depends only on your wishes, dear readers :)

    It should also be noted that this is probably the last “simple lesson”, then I will try to delve into everything aspects of programming that we went “up to the top” and continue in more detail.

    In general, those who are not interested - read the next news, and the rest - please go through.

    Python for beginners. Chapter Three "List, tuple, etc."

    Tuples.
    Tuples are used to represent an immutable sequence of heterogeneous objects. They are usually written in parentheses, but if ambiguity does not occur, then the brackets can be omitted.

    >>> t = (2, 2.05, "Hello")
    >>> t
    (2, 2.0499999999999998, 'Hello')
    >>> (a, b, c) = t
    >>> print a, b, c
    2 2.05 Hello
    >>> z, y, x = t
    >>> print z, y, x
    2 2.05 Hello
    >>> a = 1
    >>> b = 2
    >>> a, b = b, a
    >>> print a, b
    2 1
    >>> x = 12,
    >>> x
    (12,)

    As you can see from the example, the tuple can also be used on the left side of the assignment operator. The values ​​from the tuple on the left side of the assignment operator are associated with similar elements on the right side. This fact gives us such wonderful opportunities as mass initialization of variables and the return of multiple values ​​from a function at the same time. The last example demonstrates the creation of a tuple from a single element (it is often called a singleton).

    Lists

    Python has no arrays in the traditional sense of the term. Instead, lists are used to store homogeneous (and not only) objects. They are defined in three ways.

    Simple listing:
    >>> a = [2, 2.25, "Python"]
    >>> a
    [2, 2.25, 'Python']

    Convert string to list
    >>> b = list ("help")
    >>> b
    ['h', 'e', ​​'l', 'p']

    Creation using list inclusions. In this case, we take cubes of all odd numbers from 0 to 19. I plan to devote a separate lesson to this syntax.
    >>> c = [x ** 3 for x in range (20) if x% 2 == 1]
    >>> c
    [1, 27, 125, 343, 729, 1331, 2197, 3375, 4913, 6859]

    A number of operators and functions are defined for working with lists:
    len (s) Sequence length s
    x in s Checks whether a sequence element belongs to a sequence. In newer versions of Python, you can verify that a substring belongs to a string. Returns True or False
    x not in s = not x in s
    s + s1 Concatenation of sequences
    s * n or n * s Sequence of n times repeated s. If n <0, an empty sequence is returned.
    s [i] Returns the i-th element of s or len (s) + i-th if i <0
    s [i: j: d] A slice from the sequence s from i to j with step d will be considered below
    min (s) Smallest element s
    max (s)The largest element s
    s [i] = x the i-th element of the list s is replaced by x
    s [i: j: d] = t The slice from i to j (in steps of d) is replaced by (list) t
    del s [i: j : d] Removing slice elements from a sequence.

    In addition, a number of methods are defined for lists.
    append (x ) Adds an element to the end of the sequence
    count (x) Counts the number of elements equal to x
    extend (s) Adds to the end of the sequence the sequence s
    index (x) Returns the smallest i, such that s [i] == x. Raises a ValueError exception if x is not found in s
    insert (i, x) Inserts an element x in the ith space of
    pop (i)Returns the ith element, removing it from the
    reverse () sequence Reverses the order of s elements inverse
    sort ([cmpfunc]) Sorts s elements. Its own comparison function cmpfunc can be specified.

    To convert a tuple to a list, there is a list function, for a reverse operation, a tuple.

    The indexing of lists and the allocation of subsequences should be mentioned again separately (this mechanism works similarly for strings). To obtain an element, square brackets are used in which the index of the element is located. Elements are numbered from scratch. A negative index value indicates elements from the end. The first element from the end of the list (line) has an index of -1.

    >>> s = [0, 1, 2, 3, 4]
    >>> print s [0], s [-1], s [3]
    0 4 3
    >>> s [2] = -2
    >>> print s
    [0, 1, -2, 3, 4]
    >>> del s [2]
    >>> print s
    [0, 1, 3, 4]

    Things are more complicated with slices. To obtain slices of a sequence in Python, it is customary to indicate not the numbers of elements, but the numbers of "gaps" between them. Before the first element of the sequence, the interval has an index of 0, before the second - 1, and so on. Negative values ​​count the elements from the end of the line.
    In general, the slice is written in the following form:
    list [start: end: step]
    By default, the beginning of the slice is 0, the end of the slice is len (list), the step is 1. If no step is specified, the second character “:” can be omitted.
    Using a slice, you can specify a subset to insert a list into another list, even at zero length. This is convenient for inserting a list at a strictly defined position.

    >>> l = range (12)
    >>> l
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    >>> l [1: 3]
    [12]
    >>> l [-1:]
    [eleven]
    >>> l [:: 2]
    [0, 2, 4, 6, 8, 10]
    >>> l [0: 1] = [- 1, -1, -1]
    >>> l
    [-1, -1, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    >>> del l [: 3]
    >>> l
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    

    Dictionaries A

    dictionary (a hash, a predefined array) is a mutable data structure designed to store key: value elements. Everything is easily shown by example.

    Create hashes.
    >>> h1 = {1: "one", 2: "two", 3: "three"}
    >>> h2 = {0: "zero", 5: "five"}
    >>> h3 = {"z": 1, "y": 2, "x": 3}
    # Cycle on a key-value pair
    >>> for key, value in h1.items ():
    ... print key, "", value
    ...
    1 one
    2 two
    3 three
    # Key cycle
    >>> for key in h2.keys ():
    ... print key, "", h2 [key]
    ...
    0 zero
    5 five
    # Cycle by values
    >>> for v in h3.values ​​():
    ... print v
    ...
    2
    3
    1
    # Adding items from another hash
    >>> h1.update (h3)
    # The number of pairs in the hash
    >>> len (h1)
    6

    Type file.

    Objects of this type are designed to work with external data. Most often, a file on disk corresponds to this object, but this is far from always the case. File objects should support the main methods: read (), write (), readline (), readlines (), seek (), tell (), close (), etc.

    The following example shows a file copy:
    f1 = open ("file1.txt", "r")
    f2 = open ("file2.txt", "w")
    for line in f1.readlines ():
      f2.write (line)
    f2.close ()
    f1.close ()

    (this example can be written in a host of other ways, many of which are very different in terms of optimality, but this is also a topic for

    another discussion) In principle, most functions are absolutely indifferent to whether a file type object or any other object with the same methods is passed to them. So, the above example can be very easily modified to download a file from the Internet, replacing the first line in it with the following code.

    import urllib
    f1 = urllib.urlopen ("http://python.onego.ru") 

    Tasks:
    - To develop a program of "mass download" of URLs from the file urls.txt
    - To develop a program that downloads a page at the specified URL with all its contents.
    - Write a program that, having received an arbitrary list at the input, will remove all duplicate elements from it.

    Also popular now: