Python BASICS (6): List and metadata, and python Basics

Source: Internet
Author: User

Python BASICS (6): List and metadata, and python Basics

I. List

The list is a container where a group of data can be placed, and each element in the list has a location index. Each element in the list can be changed. operations on the list will affect the original list. The definition of the List is defined by "[]". elements are separated by commas (,), for example:

a = [12,'hello',15.5,True]

A list is defined above. The elements in the list can be any data type, not limited to these data types in the example.

1. Elements in the access list

The most direct method is to access the element through the location index. The index of the list starts from 0. For example, to access the first element in the above list and print it out:

print(a[1])

Print the result: "hello". The index value can be a negative number, indicating that the count starts from the end. For example:

print(a[-1])

The result is "True", indicating that the last element is obtained. Note: The negative index does not start from 0, but starts from-1 to indicate the last one.

To change a location element:

a = [12,'hello',15.5,True]a[1] = 'world'print(a)

Print results: [12, 'World', 15.5, True]. You can directly change the position of an element through the location index.

2. List slice

In Python, there is an operation method called slice. I think it is actually a syntactic sugar. How to use it is as follows:

a = [12,'hello',15.5,True]b = a[:]print(b)

The result is: [12, 'Hello', 15.5, True]. The print result is the same as that of list a, which is equivalent to copying. Let's take a look at the following example:

a = [12,'hello',15.5,True]b = a[1:3]print(b)

The result is: "['hello', 15.5]". After slicing, the elements on the first and second index are obtained. In the preceding two examples, ":" indicates the start and end of the Position Index of the element to be obtained, but does not contain the elements corresponding to the end index. If no data is written, the first index is used by default, and the last index is used later. In addition, it is very easy to obtain the list of elements calculated from the end, such:

a = [12,'hello',15.5,True]b = a[1:-1]print(b)

Result: "['hello', 15.5]" indicates that the first entry in the list ends with the last entry (but does not include the last entry ). For example:

a = [12,'hello',15.5,True]b = a[-3:3]print(b)

Result: "['hello', 15.5]" is flexible, but it can be either positive or negative, make sure that the index before the colon is smaller than the index after the colon.

3. in and not in

When we want to determine whether an element is in the list, we can use the in or not in keyword to determine whether it is in the list.

a = [12,'hello',15.5,True]b = 'hello'c = b in aprint(c)

The print result is: "True" indicates that element B exists in list.

4. "+" and extend

Let's look at the example:

a = [12,'hello',15.5,True]b = ['world',22,False]c = a + bprint(c)

Print the result: [12, 'Hello', 15.5, True, 'World', 22, False]. You can see that list a and list B are merged into a new list. Next let's look at the example:

a = [12,'hello',15.5,True]b = ['world',22,False]a.extend(b)print(a)

Print the result: [12, 'Hello', 15.5, True, 'World', 22, False]. It can be seen that extend is used to add List B to list, list merging is also achieved.

5. "*"

A = ['har'] * 4 print ()

Print the result: ['Ha ', 'ha']. Repeated elements in the list can be implemented using.

6. List common methods

A. count ()

a = ['abc','hello','abc','world']print(a.count('abc'))

Print result: 2, indicating that the string 'abc' appears twice in the list.

B. index ()

a = ['abc','hello','abc','world']print(a.index('abc'))

Print result: 0, indicating that the first occurrence of the string 'abc' in the list is indexed at The 0th position.

C. append ()

Append an element to the end of the list.

a = ['hello']a.append('world')print(a)

Print result: ['hello', 'World']. An element 'World' is added at the end of list'

D. insert ()

The append () method can only add elements at the end. If you want to add elements at any position, you need to use insert ().

a = [12,'hello',15.5,True]a.insert(2,'world')print(a)

Print the result: [12, 'Hello', 'World', 15.5, True]. You can see that the index of list a is 2, that is, a "world" is added to the third position"

E. pop ()

Pop () deletes an element from the list.

a = [12,'hello',15.5,True]a.pop()print(a)

Print result: [12, 'Hello', 15.5]. The last element is deleted. You can add an index to pop and specify the element to be deleted:

a = [12,'hello',15.5,True]a.pop(2)print(a)

Print result: [12, 'Hello', True]. The index of list a is 2, that is, the element at the third position is deleted.

F. remove ()

Pop () deletes an element through an index. When we do not know the index, but only know the element to be deleted, we can use the remove Method.

a = [12,'hello',15.5,'hello']a.remove('hello')print(a)

Print the result: [12, 15.5, 'Hello']. The first "hello" is deleted. In other words, the first matched element is deleted.

G. sort ()

Sort the elements in the list:

a = ["abc",'hello','world','Tom','Lucy']a.sort()print(a)

Printed result: ['Lucy ', 'Tom', 'abc', 'Hello', 'World'] sorts the elements of category a in the order of ASCII tables, this method is the same as the sorted method in the built-in function. If you are interested, try it yourself. If you want to sort the data in reverse order:

a = ["abc",'hello','world','Tom','Lucy']a.sort(reverse=True)print(a)

Result: ['World', 'Hello', 'abc', 'Tom ', 'Lucy']. In sort, the reverse value is True. The default value is False. In the sort method, you can add a parameter and define the sorting method by yourself. After learning functions or anonymous functions, we will introduce them again.

H. reverse ()

Sort the original list in reverse order:

a = ["abc",'hello','world','Tom','Lucy']a.reverse()print(a)

Print the result: ['Lucy ', 'Tom', 'World', 'Hello', 'abc']. This method is actually the same as the reversed () method in the built-in function. If you are interested, try it yourself.

II. for Loop

The for loop is mentioned in the previous section. Here we will learn more. For Loop usage:

a = ["abc",'hello','world','Tom','Lucy']for i in a:    print(i,end=" ")

Print the result: "abc helloworld Tom Lucy", traverse all the elements in List a, and print the elements.

I indicates the elements that are traversed each time. It is easy to use. Combined with the built-in function enumerate () mentioned above, let's see the effect:

A = ["abc", 'Hello', 'World', 'Tom ', 'Lucy'] for x, I in enumerate (a): print ("location: % d element: % s "% (x, I ))

Final result:

 

The for loop is used to traverse the location index and corresponding elements in the list one by one.

3. tuples

Tuples can be understood as special lists. Where is the Special List? Tuples are unchangeable. Use "()" to define a set of data: specifically:

a = (12,"hello",12.5,False)print(a)

Print the result: (12, 'Hello', 12.5, False ). We have defined a tuples a. After initialization, The tuples a can no longer be changed. Note: Empty tuples and 1 element tuples:

A = () # create an empty tuples B = (1,) # create a tuple containing one element

When creating a tuples containing one element, you must add a comma to avoid ambiguity.

Since tuples are immutable, they do not have as many operations and methods as the list does.

You can still obtain the corresponding elements through the location index, but cannot modify them:

a = (12,"hello",12.5,False)print(a[1])

Print the result: "hello ". The use of the list is the same. You can try to change the value of an element. Check whether it is variable.

In tuples, the "+" operation can still be used, because the original tuples are not changed, but a new tuples are formed:

a = (12,"hello",12.5,False)b = ('world',22,False)c = a + bprint(c)

Print result: (12, 'Hello', 12.5, False, 'World', 22, False)

The index () and count () methods can still be used in tuples. Similarly, these two methods do not change the original tuples. The usage method is the same as the list method. Here we will not give an example, you can try it yourself.

In addition, there is also a built-in list () method in the built-in function to convert tuples into lists. For example:

a = (12,"hello",12.5,False)b = list(a)print(b)

Print the result: [12, 'Hello', 12.5, False]. It can be seen that the list function does not change the original tuples, but generates a new list based on tuples. There is also a tuple () function in the built-in function, which converts the list into tuples. Let's give it a try.

Think about it. tuples are a special list. They can encapsulate various data types like lists, that is, lists can also be encapsulated in tuples, for example:

a = [12,'hello',15.5,True]b = ('world',22,False,a)

A special element in tuples B above is list a. As we all know, list a can be changed. When elements in a change, does it change? That is to say, the tuples are changed, is it against the above descriptions? In fact, the element sending in a changes, and the address a in the memory remains unchanged, that is, the address pointed to by variable a remains unchanged, that is, no matter how a changes, the address pointed to by a in B is unchanged, but the content in the address is changed. As mentioned above, a is just a variable name, and the variable name actually points to an address in the memory, which stores the actual content. To put it bluntly, a is an address, and the address remains unchanged. The element in a is changed to the content in the address. For example, the address is the address of your home, your home can be decorated, smashed, and changed, but the address is still the address. You can still find your home through the address. By changing the expression B on the surface of a, the content in B remains unchanged. This article is a bit profound and can be understood as much as you can, and will be gradually understood as you study in the future.

Iv. Copy Problems

The copy problem is the same as that of the list containing tuples. If the above content does not understand the copy problem, it is hard to understand it, but it does not matter.

During slicing, you can copy a list in the following way: [:]. This method is a shortest copy. What does this mean? For example:

A = [12, 'Hello', 15.5, True] B = ('World', 22, False, a) c = B [:] print ('before changing :', c) a [1] = 'nihao' print ('after changing ', c)

Running result:

We can see that although c is a copy we re-copy, c will also change when the original B sends a change. Such a copy is called a shallow copy, A new object is created in the essence of the shallow copy, but the internal reference is also a simple copy. "Reference" to put it bluntly, it is the address pointed to by the variables mentioned above, that is, the address or the address. It is just a copy. If there is a shallow copy, there will be a deep copy. In this case, we need to introduce a copy module. Example:

Import copya = [12, 'Hello', 15.5, True] B = ('World', 22, False, a) c = copy. deepcopy (B) print ('before change: ', c) a [1] = 'nihao' print ('after change', c)

Running result:

We found that the original B has changed, but the copied c has not changed. Deep copy not only creates an object, but also references all the new objects. This part of content may be difficult for students who have no foundation to understand, but it is not so difficult to understand it after learning and looking back at it later. Don't worry.

 

 

Benefits:ReplyPython booksTo obtain some well-recognized e-books learned by python.

 

Tips:The Code involved above. Beginners must think carefully and think carefully about it. I have also provided all the running results in the article. Do not look down. For beginners, the results achieved by themselves are often different from those imagined.

 

Note:The author's content is original and reprinted to indicate the source. Due to my limited ability, please contact the author for any errors or omissions. Thank you!

If you have any questions about installing or using python, you can join the QQ group: 476581018. You can also follow the latest articles in the public account series (quick scan (● 'blood' ●). You are welcome to stay tuned for the latest updates, and have more benefits for you!

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: info-contact@alibabacloud.com 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.