In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "what are the built-in data structures in Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the built-in data structures in Python"?
Python is the most popular programming language today, and even children can learn interesting programming from it. Python's simple grammar similar to that of English makes it a lingua franca and has been widely used in various fields around the world.
The omnipotence of Python lies in its built-in data structure, which makes coding simple, independent of data type, and can manipulate data as needed. First of all, let's try to understand what is a data structure? A data structure is a structure / container that can store, organize, and manage data so that it can be accessed and used effectively. The data structure is the type of data collected. There are four built-in data structures in Python. They are:
List
Dictionaries
Tuple
Set
The most commonly used data structures for developers are lists and dictionaries. Next, let's take a closer look at each data structure.
1. List
A Python list is a collection of items of any type in order. A list can have duplicate items because each item is accessed using an index, and the column item can be accessed backwards by using a negative index. Lists are mutable, which means that items can be added, deleted, or changed even after items have been created; one list can also contain another list.
(1) create a list:
Lists can be created by enclosing elements in [] square brackets, with each item separated by a comma. Taking a shopping list as an example, the syntax for creating a list is:
# Creating a list fruits = ['Apple',' Banana', "Orange"] print (type (fruits)) # returns type print (fruits) # prints the elements of the listOutput: ['Apple',' Banana', 'Orange']
(2) access list:
You can use an index to access items in a list. Each item in the list has an index associated with it, depending on where the item is in the list. Syntax for items in the access list:
# Access elements in the fruits listfruits = ['Apple',' Banana', "Orange"] print (fruits [0]) # index 0 is the first element print (fruits [1]) print (fruits [2]) Output: Apple Banana Orange
However, the index does not always have to be positive. If you want to reverse access to the list, that is, in reverse order, you can use a negative index, as shown below:
# Access elements in the fruits list using negative indexesfruits = ['Apple','Banana', "Orange"] print (fruits [- 1]) # index-1 is the last element print (fruits [- 2]) print (fruits [- 3]) Output: Orange Banana Apple
If you must return an element between two positions in the list, use a slice. You must specify the start and end indexes to get the range of elements from the list. The syntax is List_name [start: end: step]. In this case, the step size is an incremental value, and the default is 1.
# Accessing range of elements using slicingfruits = ['Apple',' Banana', "Orange"] fruits # all elements ['Apple',' Guava', 'Banana',' Kiwi'] # outputfruits [: 1] # start to endwith step 1 ['Apple',' Guava', 'Banana',' Kiwi'] # outputfruits [: 2] # start to endwith step 2 basically index 0 & 2 ['Apple' 'Banana'] # output fruits [:: 3] # start to end with step 2 basically index 0 & 3 [' Apple', 'Kiwi'] # output fruits [::-1] # start to end with step 2-reverse order [' Kiwi', 'Banana',' Guava', 'Apple'] # output
(3) add elements to the list:
You can use the append (), extend (), and insert () functions to add items to the list.
# Adding elementsfruits = ['Apple',' Banana', "Orange"] # Appendnew elements fruits.append ('Kiwi') print (fruits) Output: [' Apple', 'Banana','Orange',' Kiwi'] # Insertelements in to the listfruits.insert (1 Insertelements in to the listfruits.insert) # inserts Guava as secondelement is the list since the index is specified as 1 print (fruits) Output: ['Apple',' Guava', 'Banana','Orange',' Kiwi']
(4) remove items from the list:
Similar to adding elements, removing elements from the list is easy, and can be done using the del (), remove (), and pop () methods. To clear the entire list, you can use the clear () function.
The del () function deletes the element at the given index.
The pop () function deletes the element at a given index from the list, or it assigns the deleted element to the variable. If no index value is specified, the last element in the list is deleted.
The remove () function deletes an element based on its value.
The clear () function clears the list.
# Deleting elements from the listfruits = ['Apple',' Guava', 'Banana','Orange',' Kiwi'] # del () function del fruits [3] # delete element at index 4 print (fruits) Output: ['Apple',' Guava', 'Banana',' Kiwi'] # pop () function del_fruit = fruits.pop (2) print (del_fruit) print (fruits) Output:' Banana' ['Apple',' Guava', 'Orange' 'Kiwi'] # Remove function fruits.remove (' Apple') print (fruits) Output: ['Guava',' Banana', 'Orange',' Kiwi'] # Clear () function fruits.clear () print (fruits) Output: [] # clears the list
Other functions:
There are several other functions you can use when working with lists:
The len () function returns the length of the list.
The index () function looks for the index value of the incoming value encountered for the first time.
The count () function looks for the number of values passed to it.
The sorted () and sort () functions are used to sort the values of the list. Sorted () has a return type, while sort () modifies the original list.
# Other functions for listnum_list = [1,2,3,10,20,10] print (len (num_list)) # find length of list print (num_list.index (10)) # find index of element that occurs first print (num_list.count (10)) # find count of the element print (sorted (num_list)) # print sorted list but not change original num_list.sort (reverse=True) # sort original list print (num_list) Output: 6 32 [1, 2, 3, 10, 10 20] [20, 10, 10, 3, 2, 1]
two。 Dictionaries
Dictionaries are another unordered data structure in which elements are stored in a different order than the order in which they are inserted. This is because the index value cannot access the elements in the dictionary. In dictionaries, data is stored as key-value pairs, and element values are accessed through keys.
Image source: unsplash
(1) create a dictionary:
The dictionary is created with {} curly braces separated by colons or using the dict () function to write keys and values.
# Creating Dictionariesnew_dict = {} # empty dictionary print (new_dict) new_dict = {1: 'Python', 2:' Java'} # dictionary with elements print (new_dict) Output: {} {1: 'Python', 2:' Java'}
(2) change and increase the key-value pair:
To change the value of the dictionary, you will use the key to access the key, and then change the value accordingly. To add a value, simply add another key-value pair, as follows:
# Changing and Adding key, value pairslang_dict = {'First':' Python','Second': 'Java'} print (lang_dict) lang_dict [' Second'] = 'Clippers' # changing element print (lang_dict) lang_dict ['Third'] =' Ruby' # adding key-value pair print (lang_dict) Output: {'First':' Python','Second': 'Java'} {' First': 'Python' Second': 'Python','} {'First':' Python', 'Second':' Ruby'}
(3) access the elements in the dictionary:
Elements in the dictionary can only be accessed using keys, and values can be obtained using the get () function or just keys.
# Accessing Elementslang_dict = {'First':' Python', 'Second':' Java'} print (lang_dict ['First']) # access elements using keys print (lang_dict.get (' Second')) Output: Python Java
(4) Delete the key-value pair in the dictionary:
These are the functions in the dictionary for deleting elements.
Pop ()-deletes the value and returns the deleted value
Popitem ()-gets the key-value pair and returns the tuple of the key and value
Clear ()-clears the entire dictionary
# Deleting key, value pairs in a dictionarylang_dict = {'First':' Python','Second': 'Java',' Third': 'Ruby'} a = lang_dict.pop (' Third') # pop element print ('Value:', a) print (' Dictionary:', lang_dict) b = lang_dict.popitem () # pop the key-value pair print ('Key, value pair:', b) print (' Dictionary' Lang_dict) lang_dict.clear () # empty dictionary print (lang_dict) Output: Value: Ruby # pop element Dictionary: {'First':' Python','Second': 'Java'} Key, value pair: (' Second', 'Java') # popthe key-value pair Dictionary {' First': 'Python'} {} # empty dictionary
(5) other functions:
These are other functions that can be used with dictionaries to get key values and key-value equivalents.
# Other functions for dictionarylang_dict = {'First':' Python','Second': 'Java',' Third': 'Ruby'} print (lang_dict.keys ()) # get keys print (lang_dict.values ()) # get values print (lang_dict.items ()) # get key-value pairs print (lang_dict.get (' First')) Output: dict_keys (['First',' Second','Third']) dict_values (['Python' 'Java','Ruby']) dict_items ([(' First', 'Python'), (' Second', 'Java'), (' Third', 'Ruby')]) Python
3. Tuple
Image source: unsplash
Tuples are basically the same as lists, except that once the data enters the tuple, it cannot be changed anyway. Therefore, once a tuple is generated, no values can be added, deleted, or edited.
(1) create a tuple:
Create tuples using () parentheses or the tuple () function.
# Creating Tuplesmy_tuple = (1,2,3) # create tupleprint (my_tuple) Output: (1,2,3) # Creating Tuplesmy_tuple = (1,2,3) # create tupleprint (my_tuple) Output: (1,2,3)
(2) access the elements in the tuple:
Accessing tuple elements is similar to lists.
# access elementsmy_tuple2 = (1,2,3 MagneNew') for x in my_tuple2: print (x) # prints all the elementsin my_tuple2print (my_tuple2) print (my_tuple2 [0]) # 1st element print (my_tuple2 [:]) # all elements print (my_tuple2 [3] [1]) # this returns the 2nd character of the element atindex 3 print (my_tuple2 [- 1]) # last elementOutput: 1 23 new (1, 2, 3) 'new') 1 (1,2,3,' new') e new
(3) append elements to another tuple:
To add a value, you can use the'+ 'operator.
# Appending elementsmy_tuple = (1,2,3) my_tuplemy_tuple = my_tuple + (4,5,6) # add elements print (my_tuple) Output: (1,2,3,4,5,6)
(4) tuple assignment:
Tuple packaging and unpacking operations are useful to assign elements of another tuple to the current tuple in a row. Tuple packaging is to create tuples by adding a single value, and tuple unpacking is to assign values in tuples to variables.
# tuple packing planets = ('Earth','Mars','Jupiter') # tuple unpackinga,b,c = planets print (a) print (b) print (c) Output: Earth Mars Jupiter
4. Set
Image source: unsplash
A collection is a unique collection of unordered elements. This means that even if the data is repeated more than once, the collection is retained only once.
(1) create a collection:
Use {} curly braces to create a collection and assign values.
# Creating setsnew_set = {1,2,3,4,4,5} # create set print (new_set) Output: {1,2,3,4,5}
(2) add elements to the collection:
Use the add () function to assign values and add elements.
# Adding elements to a Setnew_set = {1,2,3} new_set.add (4) # add element to set print (new_set) Output: {1,2,3,4}
(3) set operation:
The different actions that can be performed on a collection are as follows.
The union () function merges the data from the two sets.
The intersection () function only looks for data that appears simultaneously in both sets.
The difference () function deletes the data that exists in both collections and outputs only the data that exists in the passed collection.
The symmetric_difference () function performs the same operation as the difference () function, but outputs the data retained in both collections.
The clear () function clears the collection.
# Operations on set my_set = {1,2,3,4} my_set_2 = {3,4,5,6} print (my_set.union (my_set_2)) print (my_set.intersection (my_set_2)) print (my_set.difference (my_set_2)) print (my_set.symmetric_difference (my_set_2)) my_set.clear () print (my_set) Output: {1,2,3,4,5 6} {3,4} {1,2} {1,2,5,6} set () to this point I believe that you have a deeper understanding of "what is the built-in data structure in Python", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.