Summary of common data types in Python and summary of python Data Types

Source: Internet
Author: User

Summary of common data types in Python and summary of python Data Types

Python provides multiple data types to store data item sets, including sequences (list and meta-group tuple), ing (such as Dictionary dict), and set. The following describes these types of data:

Sequence 1

1. list

A list is an ordered set. The elements in a list are variable and can be added or deleted at any time.

(1) create a list

Test in the command line as follows:

>>> L1 = [1,2,3]>>> L1[1, 2, 3]>>> L2 = ['abc']>>> L2['abc']>>> L3 = ["a","b","c"]>>> L3['a', 'b', 'c']

Note that the string must be enclosed in quotation marks.

List is very effective for creating a list of strings, for example:

>>> L = list("Python")>>> L['P', 'y', 't', 'h', 'o', 'n']

(2) access list

Access Based on indexes. Note that the access is not out of bounds, which is particularly similar to the array:

>>> L[0]'P'>>> L[-1]'n'

(3) Add new elements

Use the append () method to append a new element to the end of the list. insert () can add a new element to a specific position.

(4) Delete an element

You can use the pop () method to delete an element. Execute L. pop () to delete the last element of the list. If it is a specific position, pop (2) and 2 indicate a position.

(5) Replacement

It's easy to replace, just index it directly.

(6) print

>>> L = ['a','b','c']>>> for i in L: print(i) abc

2. tuple

(1) Create

Unlike list, tuple is generally enclosed by () and tested in the command line as follows:

T= 1,2,3>>> T(1, 2, 3)>>> T = (1,2,3)>>> T(1, 2, 3)>>> T = "abc">>> T'abc'

Create null tuples: T = ()

Define the tuples of an element:

>>> T = (1)
>>> T
The running result is correct, and it looks true, but this definition is not correct. This definition is not tupel, but 1, because parentheses () can represent tuple, it can also represent parentheses in the mathematical formula, which leads to ambiguity. Therefore, Python stipulates that in this case, the calculation result is naturally 1 by parentheses. Therefore, you must add a comma when defining a tuple containing an element, as shown below:

>>> T = (1,)>>> T(1,)

(2) Access

Direct indexing is good, as shown below:

>>> T =(1,2,3)>>> T[1]2

(3) Change

The tuple defined above remains unchanged, but we can modify it by defining the list in tuple:

>>> T = (1,2,['a','b'])>>> T[2][0]'a'>>> T[2][0] = 'c'>>> T(1, 2, ['c', 'b'])

In tuple, although the elements cannot be modified, We Can concatenate them:

>>> T1 = [1,2,3]>>> T2 = [4,5,6]>>> T3 = T1 + T2>>> T3[1, 2, 3, 4, 5, 6]

3. String

(1) Create

>>> str = "Hello Python">>> str'Hello Python'

(2) Access

>>> str[0]'H'

(3) add

>>>str = "hello ">>>str = "Python">>> str3 = str1 + str2>>> str3'Hello Python'

4. General sequence operation methods

(1) Index

Used in access sequence elements, as follows:

>>> L = ['a','b','c']>>> L[1]'b'>>> T = (1,2,3)>>> T[0]1>>> str = "Python">>> str[4]'o'

(2) fragment

Fragments are used to access elements within a certain range. fragments are usually implemented by two indexes separated by colons. The following are common examples:

>>> a = list(range(10))>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> b = a[1:5]>>> b[1, 2, 3, 4]>>> c = a[-3:-1]>>> c[7, 8]>>> d = a[1:10:2]>>> d[1, 3, 5, 7, 9]

Binary ing (dictionary)

Each element in the ing has a professional name called a key. The dictionary is the only built-in ing type in Python. We will introduce it in detail:

(1) Key type

A dictionary (dict) is a container dictionary that stores unordered key-value ing (key/value) data.

The key must be unique. In Python, numbers, strings, and metadata are designed to be immutable types, while common lists and sets are variable. Therefore, lists and sets cannot be used as Dictionary keys. Keys can be any unchangeable type, which is the most powerful dictionary in Python.

(2) create

>>> d = {}>>> d[1] = 1>>> d{1: 1}>>> d['cat'] = 'Lucy'>>> d{1: 1, 'cat': 'Lucy'}

(3) Search

Dict searches for values by key, indicating the relationship of meaning. You can access dict through d [key:

>>> d['cat']'Lucy'

(4) Traversal

>>> d = {}>>> d['cat'] = 'Lucy'>>> d['dog'] = 'Ben'>>> for key in d:print(key + ":",d[key])


cat: Lucydog: Ben

(5) advantages and disadvantages

The first feature of dict is that the search speed is fast, and the search speed is irrelevant to the number of elements, while the search speed of list gradually decreases with the increase of elements; the second feature is that the stored key-value pairs have no order. The third feature is that the elements obtained as keys are immutable, so the list cannot be used as keys.

The disadvantage of dict is that it occupies a large amount of memory and wastes a lot of content.

Dict establishes a series of ing relationships, while set creates a series of unordered, non-repeating elements.

(1) Create

You can create a set by calling set () and passing in a list. The list element is used as the set element.

>>> S = set([1,2,3])>>> S{1, 2, 3}

Repeated elements are automatically filtered in the Set, for example:

>>> S = set([1,1,2,3,4,5,4])>>> S{1, 2, 3, 4, 5}

(2) Add

Add (). You can add duplicate elements, but this does not work:

>>> S.add(4)>>> S{1, 2, 3, 4, 5}>>> S.add(9)>>> S{1, 2, 3, 4, 5, 9}

(3) Delete

>>> S. remove (9)
>>> S

{1, 2, 3, 4, 5}
(4) intersection and Union

Set can be regarded as a set of unordered and non-repeating elements in the mathematical sense. Therefore, two sets can be used for intersection and union in the mathematical sense:

>>> S1 = set([1,2])>>> S2 = set([2,3])>>> S1&S2{2}>>> S1|S2{1, 2, 3}

The only difference between set and dict is that the corresponding value is not stored. However, the principle of set is the same as that of dict. Therefore, it cannot be placed into a variable object, because it is impossible to determine whether two mutable objects are equal, it is impossible to ensure that "No repeated elements" are in the set"

Four main differences between list, tuple, dict, and set

1. list

List is a set of ordered elements enclosed by square brackets;

List can be used as an array starting with 0 subscripts. The first element of any non-empty list is always L [0], and the negative index starts counting forward from the end of the list to access the element. The last element of any non-empty list is always L [-1];

The sharding function is available. You can add two lists;

Append a single element to the end of the list;

Insert inserts a single element into the list;

Extend is used to connect to the list and use a list parameter for calling;

Append accepts a parameter, which can be any data type and is simply appended to the end of the list;

Index searches for the first appearance of a value in the list and returns the index value;

To test whether a value is in the list, use in. If the value exists, True is returned; otherwise, False is returned;

Remove the first appearance of deleting a value from the list;

Pop can delete the last element of the list, return the value of the deleted element, and delete the value of the specified position with the index;

2. tuple

Tuple is an immutable list. Once a tuple is created, it cannot be changed in any way;

Define tuple to enclose the entire element set in parentheses and an ordered set;

The index of a tuple starts from 0, so the first element of a non-empty tuple is always t [0];

Negative index and list are counted from the end of tuple;

Slice can also be used like list. When a tuple is split, a new tuple is generated;

There are no append, extend, remove or pop methods, and index methods;

You can use in to check whether an element exists in tuple.

3. dict

Dict defines the one-to-one correspondence between keys and values. Each element is a key-value pair;

The entire element set is enclosed in braces and ordered;

Value can be obtained through key, but key cannot be obtained through vaule;

Duplicate keys cannot exist in a dict, and keys are case sensitive;

Keys can be numbers, strings, tuples, and other unchangeable types;

Using del, you can use the key to delete independent elements in dict;

Clear can be used to clear all elements in dict.

4. set

Set creates a series of unordered, non-repeating elements;

You can create a set by calling set () and passing in a list. The list element will be the set element;

The only difference between set and dict is that the corresponding value is not stored.

The above is a summary of all the Python data types, hoping to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.