
I continue my undertaking. This article is a logical continuation of the
first . It was a pleasure to read your comments. I hoped that this cycle of articles would be useful for someone, but I didn’t assume that there would be quite a lot of people interested. It makes the case more serious and responsible.
Without further ado, immediately to the point.
As mentioned earlier, almost everything we are dealing with when programming in python is objects. Object types can be either built-in or described by the programmer using classes. This article focuses on built-in object types. They are:
- Numbers
- Strings
- Tuples
- Lists
- Dictionaries
- Sets
Numbers, strings and tuples
')
The reason that these types turned out to be summarized in one section lies in one very important point. Without an understanding of which can be made difficult to detect errors. The fact is that these types, unlike lists and dictionaries, are immutable objects. Those. creating them once - it is not possible to change their meaning. A fair question arises: how then do the following instructions work?
>>> x = 2
>>> x
2
>>> x = 3
>>> x
3
>>> x = 'string'
>>> x
'string'
The instruction x = 2 creates a numeric object with the value 2 and assigns a reference to this object to the variable x. Next, the instruction x = 3 creates a new numeric object with a value of 3 and assigns a reference to it to the variable x. And an object with a value of 2 is deleted from the memory by the automatic garbage collector, since The last link to this object was lost.
Due to this the following is true:
>>> x = y = 3 # x y 3
>>> x = 2 # x 2
>>> x
2
>>> y # y - 3
3
The topic will be mentioned about the is operator. This operator returns the value True when to the left and right of it are variables containing pointers to the same object. The question arises about the strange behavior of this operator:
>>> x = 2
>>> y = 2 #
>>> x is y # False
True
Here it’s about the internal interpreter caching mechanisms. To optimize the speed of execution when declaring a numeric or short string object, a reference and value pair is created in the cache. And in the future when declaring the same object, a new object is not created, but the one already created is used. This leads to the conclusion that the is operator is invalid for numeric and string data types.
Then everything is simple!
Types of numeric literals:
- integers of unlimited length - the interpreter itself will determine the need to use objects of unlimited length and make the necessary transformations. No more need to keep an eye on overflows.
- Floating point numbers
- octal and hexadecimal numbers
- complex numbers
Some operations on numbers:
>>> print 2 ** 150 # 2 150
1427247692705959881058285969449495136382746624
>>> print int(5.89),round(5.89),round(5.89,1) # , , 1
5 6.0 5.9
>>> import math
>>> math.pi
3.1415926535897931
>>> print math.sin(math.pi/2)
1.0
>>> import random
>>> random.randint(1,100) # 1 100
19
Lines:
Strings in apostrophes and in quotes are the same thing.
Triple Quotes Strings - You can enclose a whole block of strings in triple quotes, for example, an entire HTML or XML document.
Unformatted strings - strings of the form r "\ n \ t" - the sequences in such a string will not be replaced by specials. Characters
Unicode character strings - u'string '# loses relevance in version 3.0
more about changes 3.0Basic operations on strings:
>>> print str (len ('string')) * 3 # len () - returns the number of characters in a string
666 # * - overloaded statement that repeats a line a specified number of times
>>> 'r' in 'string' # in operator returns True if the substring is found in the string
True
>>> 'string'.replace (' r ',' ') # replacing one substring with another
'sting'
>>> 'string'.find (' ri ') # returns the offset number of the required substring
2
>>> 'a, b, c'.split (', ') # function of splitting into substrings by the specified character or substring
['a', 'b', 'c']
More complete information about string methods can be obtained by entering the help (str) command in interactive mode.
Also, the lines have already been described by my future co-author of this series of articles
here.Indexing, selection and slices of data sequences.
I think that the elements of a string can be accessed by their indices, as in an array — you don’t need to tell for a particularly long time.
>>> 'string'[1]
't'
>>> 'string'[-2] #
'n'
A slice is a fairly powerful tool for retrieving data from sequences, which is used not only in rows but also in collections, which will be discussed in this article below.
General form:
S [i: j: h], where S is a string, i is the offset value, the left border (inclusive), j is the offset value, the right border (it is not included in the slice), h is the step value.
Examples:
>>> 'string' [0: 4]
'stri'
>>> 'string' [: - 2]
'stri'
>>> 'string' [0: 5: 2]
'srn'
>>> 'string' [0: 5: -2]
'nrs'
Speaking of strings, of course, you can not forget about regular expressions. In Python, to use them, you must import the
re module
I hope that they will be able to talk separately.
Tuples
A tuple is an ordered, immutable collection of objects of arbitrary types, supporting an arbitrary number of nesting levels.
The basics of the syntax are also described in the
article clegLists and dictionaries
Lists and dictionaries are mutable embedded data types. Which means, if we go back to where we started the conversation, what if we create a list Y, then assign the assignment X = Y, and then change X, then Y will also change. You need to follow this closely! To prevent this from happening, you need to create a new object equivalent to the original one, for example, like this: X = Y [:]
Illustration:
>>> M = L = range(2,12,3)
>>> print M,L
[2, 5, 8, 11] [2, 5, 8, 11]
>>> L[2] = 112
>>> print M,L
[2, 5, 112, 11] [2, 5, 112, 11]
>>> M = L[:]
>>> L[2] = 0
>>> print M,L
[2, 5, 112, 11] [2, 5, 0, 11]
Or, if you want to ensure the immutability of the created object - use tuples instead of lists.
Lists are a tremendously flexible tool, representing an ordered collection of elements, which can include any kind of object with any level of nesting.
Dictionary - is an unordered collection of objects, access to the elements of which is provided not by using an offset, but by using a key.
For the basics of syntax, you can also go to the
article clega
Here I will only make some additions and comments on the use of dictionaries:
- sequence operations are not applicable to dictionaries, since dictionaries are not a sequence, but a mapping.
- Keys do not have to be strings. In the role of keys can be any immutable objects. Those. If we consider the built-in data types, then these are numbers, strings, and tuples. It is clear that when using numbers, the dictionary turns into a similarity of the list, however, it remains unorganized. Using tuples as keys, it is possible to use composite keys. Instances of user classes can also act as keys, provided they implement certain methods that indicate to the interpreter that the object is immutable.
Sets
Sets are containers for other objects. Sets are created with the built-in
set function and support typical mathematical operations on sets.
>>> M = set('habrahabr')
>>> L = set(['h','a','h','a'])
>>> M, L
(set(['a', 'h', 'r', 'b']), set(['a', 'h']))
>>> M & L
set(['a', 'h'])
>>> M | L
set(['a', 'r', 'h', 'b'])
>>> M - L
set(['r', 'b'])
>>> bool(M - L)
True
>>> pusto = set()
>>> bool(pusto)
False
The elements of the set can be any immutable objects.
After we have done certain operations on sets - they can be placed back into the list, for example, like this:
>>> S = []
>>> for i in M - L:
... S.append(i)
...
>>> S
['r', 'b']
That's all for today.
Using the terminology of
Radio-T, I want to ask a question :) Where do you think the degree of geekiness can be turned on? If up, then in my opinion, cycles and branching should be disclosed only in terms of the features inherent in Python.
Thanks for attention! We continue :)