Python Basics - data types

Python Basics - data types

There are six standard data types in Python

  • Number
  • String (string)
  • List
  • Turple (tuple)
  • Set
  • Dictionary

Immutable data (3): Number, String, Turple

Variable data (3): List, Set, Dictionary

Number type

Classification of digital types

int, float, bool and complex (plural) are supported in Python.

Operation rules of numeric type

Addition, subtraction, multiplication, division, modulus and power in mathematical operation

# addition
>>> 3+2
5
# subtraction
>>> 3-2
1
# multiplication
>>> 3*2
6
# division
>>> 3/2
1.5
# Rounding Division
>>> 3//2
1
# Power
>>> 3**2
9
# Take mold
>>> 12 % 7
5

Note that the division of Python values contains two operators: / returns a floating-point number and / / returns an integer

String type

Representation of string

There are many forms of strings in Python. You can use single quotation marks ('...'), double quotation marks ("..."), You can also use backslash \ to escape special characters.

>>> 'hello'
'hello'
>>> "hello"
'hello'
>>> 'doesn\'t'
"doesn't"
Splicing and copying of strings

The plus sign + is the connector of the string, the asterisk * indicates the copy of the current string, and the number combined with it indicates the number of copies.

>>> 'hello' + ' world' + '!'
'hello world!'
>>> 'hello' * 2
'hellohello'
Slicing of strings

Strings can be accessed by index subscripts. The first character index is 0. A single character has no type, but a string with a length of one.

Syntax format of string interception:

Variable [head subscript: tail subscript]

Note: the index value starts with 0 and - 1 is the position from the end

>>> word = 'Python'
>>> word[0]
'P'
>>> word[5]
'n'
>>> word[-1]
'n'
>>> word[-5]
'y'
>>> word[-6]
'P'

String index can get a single character, and string slice can get sub strings.

>>> word = 'Python'
>>> word[0:2]
'Py'
>>> word[2:5]
'tho'

The slice index has a default value. When the start index is omitted, it defaults to 0. When the end index is omitted, it defaults to the end of the string.

>>> word = 'Python'
>>> word[:2]
'Py'
>>> word[4:]
'on'
>>> word[-2:]
'on'

Slice can be understood as follows: the index is regarded as pointing between characters. The left side of the first character is marked as 0, the right side of the last character is marked as n, and n is the length of the string. for example

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

For the slice with non negative index, if the index does not exceed the limit, the length of the slice is the difference between the start and end indexes. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error:

>>> word = 'Python'
>>> word[32]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, if the index in the slice is out of bounds, it will be processed automatically

>>> word = 'Python'
>>> word[4:42]
'on'
>>> word[:42]
'Python'

Strings in Python cannot be modified. They are immutable. Therefore, assigning a value to a position of the string index will produce an error:

>>> word = 'Python'
>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Summary:

  • Backslash \ used to indicate escape. You can use r to make the backslash not escape
  • Strings can be concatenated with + and repeated with * operator
  • There are two indexing methods in Python strings: one is from left to right, starting from 0, and the other is from right to left, starting from - 1
  • Strings in Python cannot be changed

List type

The list can appear as a comma separated value within square brackets. The data items of the list do not need to have the same type.

List creation

Create a list, as long as the different data items are separated by commas and enclosed in square brackets.

>>> squares = [1, 4, 9, 16]
>>> squares
[1, 4, 9, 16]
List operation

Index, slice, iteration, length, operation (addition, multiplication) *, check member

Like strings, lists support indexing and slicing

>>> squares[0]
1
>>> squares[-1]
16
>>> squares[-3:]
[4, 9, 16]

All slicing operations return a new list containing the requested elements. This means that the following slicing operations return a shallow copy of the list:

>>>squares[:]
[1, 4, 9, 16]

The list also supports splicing operations:

>>> squares + [25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike the string of immutable, the list is a mutable type, that is, its own content can be changed:

>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64
>>> cubes
[1, 8, 27, 64, 125]

It is also possible to assign a value to the slice. You can even change the size of the list or empty the whole list:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

The built-in function len() can act on the list and calculate the length of the list

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

The + and * operators of the list are similar to strings+ For combined lists, * for duplicate lists.

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> ['hi'] * 4
['hi', 'hi', 'hi', 'hi']

Keywords of list check members: in, not in

>>> # The element exists in the list
>>> 3 in [1, 2, 3]
True
>>> # The element does not exist in the list
>>> 1 not in [1, 2, 3]
False

Iterative operation of list for x in y

>>> for x in [1, 2, 3]:
...     print(x)
...
1
2
3

Tuple type

Python tuples are similar to lists, except that the elements of tuples cannot be modified.

Tuples use parentheses and lists use square brackets.

Tuple creation

The creation of tuples is very simple. You only need to add elements in parentheses and separate them with commas

>>> t = 12345, 54321, 'hello!'
>>> t
(12345, 54321, 'hello!')
>>> t1 = ('java', 'php', 'python')
>>> t1
('java', 'php', 'python')
>>> # Create empty tuple
>>> t2 = ()
>>> t2
()
>>> # Type judgment
>>> type(t2)
<class 'tuple'>

Note: when a tuple contains only one element, you need to add a comma after the element, otherwise the bracket will be used as an operator

>>> t3 = (50)
>>> type(t3)
<class 'int'>

>>> t4 = (50,)
>>> type(t4)
<class 'tuple'>
Tuple operation

Index, slice, iteration, length, operation (addition, multiplication) *, check member

Tuples are similar to strings. The subscript index starts from 0 and can be intercepted, combined, etc

>>> t = 12345, 54321, 'hello'
>>> t[0]
12345
>>> t[-1]
'hello'

Tuples are immutable types. Assigning values to tuples will cause errors

>>> t = 12345, 54321, 'hello'
>>> t[0] = 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Tuples, like lists, can be sliced and intercepted

>>> a = (1, 2, 3, 4, 5, 6)
>>> a[2:]
(3, 4, 5, 6)
>>> a[:3]
(1, 2, 3)

The built-in function len() can act on tuples and calculate the number of tuple elements

>>> a = (1, 2, 3, 4, 5, 6)
>>> len(a)
6

The + and * and string types of tuples, + are used to combine tuples and * are used for repeating lists

>>> (1,2,3)+(4, 5, 6,)
(1, 2, 3, 4, 5, 6)
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Keywords of tuple check member: in, not in

>>> 1 in (1,2,3,)
True
>>> 1 not in (1, 2, 3,)
False

Iteration of tuples

>>> for x in (1, 2, 3,):
...     print(x)
...
1
2
3

Collection type

A collection is an unordered sequence of non repeating elements.

You can create a collection with curly braces {} or the set() function.

Note: to create an empty collection, you can only use set() instead of {}, because curly braces {} create an empty dictionary

Collection creation

Create format:

param = {value1, value2, ...}
or
set(value)
>>> # Collections are unordered and not repeated
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> basket
{'orange', 'pear', 'banana', 'apple'}
>>> # The set function creates a collection
>>> a = set('abracadabra')
>>> a
{'a', 'c', 'r', 'd', 'b'}
>>> # Set derivation creation
>>> b = {x for x in 'abracadabra' if x not in 'abc'}
>>> b
{'d', 'r'}
Collection operation

Add elements, remove elements, calculate the number of collection elements, empty the collection, and check the members of collection elements

The format of the added element is as follows:

s.add(x)

Adding a collection element is to add the element to the collection. If the element already exists, no operation will be performed. Examples are as follows:

>>> a = set('abracadabra')
>>> a
{'a', 'c', 'r', 'd', 'b'}
>>> # Add a collection element that does not exist
>>> a.add('e')
>>> a
{'a', 'e', 'c', 'r', 'd', 'b'}
>>> # Add an existing collection element
>>> a.add('a')
>>> a
{'a', 'e', 'c', 'r', 'd', 'b'}

There is another method, which can also add elements, and the parameters can be lists, tuples, dictionaries, etc. the syntax is as follows:

s.update(x)

x can have multiple, separated by commas.

>>> numbers = {1, 2, 3, 4 }
>>> numbers
{1, 2, 3, 4}
>>> type(numbers)
<class 'set'>
>>> numbers.update({'a', 'b'})
>>> numbers
{'a', 1, 2, 3, 4, 'b'}
>>> numbers.update(('apple', 'banana',), [6, 7, 8])
>>> numbers
{1, 2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}

Removing Elements

The syntax format is as follows:

s.remove(x)

Remove element x from the collection and an error occurs if the element does not exist.

>>> numbers = {1, 2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}
>>> numbers
{1, 2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}
>>> numbers.remove(1)
>>> numbers
{2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}
>>> numbers.remove('haha')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'haha'

In addition, there is another method to remove the elements in the collection. If the collection elements do not exist, no error will be sent. The format is as follows:

s.discard(x)

>>> numbers = {2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}
>>> numbers
{2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}
>>> numbers.discard('haha')
>>> numbers
{2, 3, 4, 6, 7, 8, 'b', 'banana', 'a', 'apple'}

You can also set to randomly delete an element in the collection. The syntax format is as follows:

s.pop()

thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
>>> x = thisset.pop()
>>> print(x)
Taobao
>>> thisset
{'Runoob', 'Facebook', 'Google'}
>>> thisset.pop()
'Runoob'

Element format of calculation set

The syntax format is as follows:

len(s)

>>> a = {1, 2, 3, 4}
>>> len(a)
4

Empty collection

The syntax format is as follows:

s.clear()

>>> a = {1, 2, 3, 4}
>>> a.clear()
>>> a
set()

Check whether the collection member exists

The syntax format is as follows

x in s

x not in s

Judge whether the element exists in the collection. If it exists, return True and if not, return False. Examples are as follows:

>>> a = {1, 2, 3, 4}
>>> 1 in a
True
>>> 1 not in a
False

Dictionary type

Dictionaries are indexed by keywords, which can be of any immutable type, usually strings or numbers. If a tuple contains only strings, numbers or tuples, the tuple can also be used as a keyword, but if the tuple contains variable objects directly or indirectly, it cannot be used as a keyword. Lists cannot be used as keywords because they can be changed by indexing, slicing, or local methods such as append() and extend().

The best way to understand a dictionary is to think of it as a set of key value pairs. Keys must be unique (in a dictionary). Each key = > value pair of the dictionary is separated by a colon, and each key value pair is separated by a comma. The whole dictionary is included in curly braces {}. The format is as follows:

d = {key1 : value1, key2 : value2}
Dictionary creation

To create a dictionary, just separate each key value pair with a comma, separate each key value with a colon, and surround it with curly braces

>>> tel = {'jack': 4098, 'sape':4139}
>>> a = {}
>>> a
{}
>>> # Dictionary derivation create dictionary
>>> {x: x**2 for x in (2, 4, 6)}
>>> {2: 4, 4: 16, 6: 36}
>>> # When the keyword is a simple string, sometimes you can specify key value pairs directly through keyword parameters
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
Dictionary operation

Access, modify, delete, check members, iteration

To access the dictionary, put the corresponding key in square brackets, as follows

>>> tel = {'jack': 4098, 'sape':4139}
>>> tel['jack']
4098

If you access a key that does not exist in the dictionary, an error will be generated:

>>> tel['lili']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'lili'

The way to add new content to the dictionary is to add new key value pairs, or modify or delete existing key value pairs. An example is as follows

>>> tel = {'jack': 4098, 'sape':4139}
>>> tel
{'jack': 4098, 'sape': 4139}
>>> tel['jack'] = 4099
>>> tel
{'jack': 4099, 'sape': 4139}
>>> tel['lucy'] = 4210
>>> tel
{'jack': 4099, 'sape': 4139, 'lucy': 4210}

A dictionary that can delete a single element can also empty the dictionary. Emptying requires only one operation. To explicitly delete a dictionary, use the del command. An example is as follows:

>>> # Delete single element
>>> del tel['jack']
>>> tel
{'sape': 4139, 'lucy': 4210}
>>> # Delete dictionary
>>> del tel
>>> # Empty dictionary
>>> dic = {'jack': 4039, 'sape': 4139}
>>> dic.clear()
>>> dic
{}

Keywords in and not in to check whether members exist

>>> tel = {'jack': 4039, 'sape':4139}
>>> 'jack' in tel
True
>>> 'jack' not in tel
False

When looping in the dictionary, the keyword and the corresponding value can be taken out at the same time with the items() method

>>> tel = {'jack': 4039, 'sape':4139}
>>> for k, v in tel.items():
...     print(k, v)
...
jack 4039
sape 4139

When looping through a sequence, you can use the enumerate() function to remove the index position and its corresponding value at the same time

>>> for i, v in enumerate(['tic', 'toe', 'tac']):
...     print(i, v)
...
0 tic
1 toe
2 tac

Tags: Python

Posted by delboy1978uk on Thu, 12 May 2022 12:12:25 +0300