logo

Cum să inițializați o listă în Python?

Orice obiect Python poate fi conținut într-un grup de valori ordonate într-o listă Python. Deoarece lista este o structură de date mutabilă în Python, putem adăuga, elimina sau modifica valorile existente în acest container. Spre deosebire de seturi, lista permite numeroase instanțe de aceeași valoare și le tratează pe fiecare ca pe un articol diferit. În acest tutorial, vom învăța cum să inițializam un obiect listă în Python.

Inițializați listele folosind parantezele pătrate

Folosirea unei paranteze pătrate este o modalitate de a inițializa o listă fără valori dacă dorim să construim o listă goală în Python fără valori. Pentru a inițializa o listă, trebuie doar să specificăm o pereche de paranteze drepte cu sau fără valori ale elementului.

Cod

 # Python program to show how to initialize a list using square brackets # Initializing an empty list list_ = [] print('An empty list: ', list_) # Initializing a list with some values list_ = [1, 3, 5, 7] print('A non-Empty list: ', list_) 

Ieșire:

 An empty list: [] A non-Empty list: [1, 3, 5, 7] 

Utilizarea funcției list() încorporată pentru a inițializa o listă

Funcția list() din Python construiește lista, un obiect iterabil. Prin urmare, aceasta este o altă modalitate de a crea o listă Python goală fără date în acest limbaj de codare.

Un obiect iterator, o secvență care permite iterația sau un container pot fi toate iterabile. O nouă listă goală este construită dacă nu este dată nicio intrare.

Cod

 # Python program to show how to initialize a list using the built-in list function # Initializing an empty list list_ = list() print('An empty list: ', list_) # Initializing a non-empty list list_ = list([1, 2, 3]) print('A non-empty list: ', list_) 

Ieșire:

 An empty list: [] A non-empty list: [1, 2, 3] 

Metoda parantezelor pătrate este favorizată față de funcția încorporată list() deoarece este mai clară și mai ilustrativă.

Utilizarea listelor de înțelegere pentru a inițializa o listă

Putem folosi abordarea de înțelegere a listei pentru a seta parametrii impliciti ai listei. Acesta cuprinde o expresie cuprinsă între paranteze drepte, o instrucțiune for și o instrucțiune opțională if care poate urma sau nu. Orice element pe care dorim să-l adăugăm în listă poate fi scris ca expresie. Expresia ar fi 0 dacă utilizatorul ar inițializa lista cu zerouri.

Înțelegerea listelor este o abordare elegantă, simplă și binecunoscută pentru construirea unei liste bazate pe un iterator.

Cod

 # Python program to show how to initialize a list using list comprehension # Initializing a list list_ = [item for item in range(10)] print('The list was created using list comprehension: ', list_) 

Ieșire:

 The list was created using list comprehension: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Această tehnică inițializează listele mult mai rapid decât buclele for și while ale lui Python.

Inițializați o listă Python folosind operatorul *

O altă modalitate de a inițializa o listă în Python este utilizarea operatorului *. Se creează o listă cu mai multe valori. Sintaxa utilizării acestui operator este [element] * n. Aici n este de câte ori dorim să repetăm ​​elementul din listă.

Această metodă ajută atunci când dorim să inițializam o listă de lungimi predefinite.

Cod

 # Python program to show how to use the * operator to initialize a list list_ = [5]*10 print (list) 

Ieșire:

 [5, 5, 5, 5, 5, 5, 5, 5, 5] 

Această metodă este foarte eficientă și cea mai rapidă modalitate de a crea o listă. Vom compara timpul necesar metodelor mai târziu în acest tutorial.

Singurul dezavantaj al folosirii acestui operator pentru a inițializa o listă Python este atunci când trebuie să creăm o listă 2D, deoarece această metodă va crea doar o listă superficială, adică va crea un singur obiect listă și toți indicii se vor referi la aceasta. obiect care va fi foarte incomod. Acesta este motivul pentru care folosim înțelegerea listelor atunci când trebuie să creăm liste 2D.

Folosind o buclă for și append()

Vom crea o listă goală și vom rula o buclă for pentru a adăuga elemente folosind funcția append() a listei.

Cod

 # Python program to show how to use a for loop to initialize a list arr = [] for i in range(1000): arr.append(0) 

Utilizarea unei bucle While pentru a inițializa o listă

Putem folosi o buclă while la fel cum am folosit bucla for pentru a inițializa o listă.

Cod

 # Python program to initialize a list using a while loop # Creating an empty list array = [] # Declaring counter variables i = 0 # Starting a while loop while(i <10): array.append(0) i +="1" print(array) < pre> <p> <strong>Output:</strong> </p> <pre> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] </pre> <h2>Time Complexity</h2> <p>Let us now see how long each of the described approaches will take. We will initialize a list of 100000 elements 1000 times. We will calculate the average time each method takes to perform this task.</p> <p> <strong>Code</strong> </p> <pre> # Python program to see the time taken by various methods to initialize a list # importing the time module to calculate the time taken by a chunk of code import time # initializing the lists for various methods forLoop = [] whileLoop = [] listComprehension = [] starOperator = [] # repeating the process of generating a list of 100000 elements 500 times # Then calculate the average time taken by the methods for i in range(1000): # starting time of the execution begin = time.time() # declaring an empty list list_ = [] # running a for loop and iterating it 100000 times for i in range(100000): list_.append(0) # stoping time of the execution end = time.time() forLoop.append(end - begin) # starting time of the execution begin = time.time() # declaring an empty list list_ = [] i = 0 # COunter variable # running a while loop and iterating it 100000 times while i <100000: 100000 list_.append(0) i +="1" end="time.time()" whileloop.append(end - begin) begin="time.time()" # using a list comprehension to initialize the for in range(100000)] listcomprehension.append(end astrick (*) operator * staroperator.append(end print('the average execution time of loop is: ', sum(forloop) 1000) while sum(whileloop) sum(listcomprehension) taken operator: sum(staroperator) < pre> <p> <strong>Output:</strong> </p> <pre> The average execution time of for loop is: 0.01166958212852478 The average execution time of the while loop is: 0.01916465663909912 The average execution time of list comprehension is: 0.005084690093994141 The average execution time was taken of * operator: 0.00028331947326660156 </pre> <p>We can see that for and while loops take almost the same execution time. However, for loop is a little better than the while loop.</p> <p>List comprehension shows much better performance than the for and while loops. It is 2-3 times faster than the loops. Thus, list comprehension is much more efficient than the append() function of the lists.</p> <p>The * operator has shown the best performance out of all the four methods.</p> <hr></100000:></pre></10):>

Complexitatea timpului

Să vedem acum cât timp va dura fiecare dintre abordările descrise. Vom inițializa o listă de 100000 de elemente de 1000 de ori. Vom calcula timpul mediu necesar fiecărei metode pentru a îndeplini această sarcină.

Cod

 # Python program to see the time taken by various methods to initialize a list # importing the time module to calculate the time taken by a chunk of code import time # initializing the lists for various methods forLoop = [] whileLoop = [] listComprehension = [] starOperator = [] # repeating the process of generating a list of 100000 elements 500 times # Then calculate the average time taken by the methods for i in range(1000): # starting time of the execution begin = time.time() # declaring an empty list list_ = [] # running a for loop and iterating it 100000 times for i in range(100000): list_.append(0) # stoping time of the execution end = time.time() forLoop.append(end - begin) # starting time of the execution begin = time.time() # declaring an empty list list_ = [] i = 0 # COunter variable # running a while loop and iterating it 100000 times while i <100000: 100000 list_.append(0) i +="1" end="time.time()" whileloop.append(end - begin) begin="time.time()" # using a list comprehension to initialize the for in range(100000)] listcomprehension.append(end astrick (*) operator * staroperator.append(end print(\'the average execution time of loop is: \', sum(forloop) 1000) while sum(whileloop) sum(listcomprehension) taken operator: sum(staroperator) < pre> <p> <strong>Output:</strong> </p> <pre> The average execution time of for loop is: 0.01166958212852478 The average execution time of the while loop is: 0.01916465663909912 The average execution time of list comprehension is: 0.005084690093994141 The average execution time was taken of * operator: 0.00028331947326660156 </pre> <p>We can see that for and while loops take almost the same execution time. However, for loop is a little better than the while loop.</p> <p>List comprehension shows much better performance than the for and while loops. It is 2-3 times faster than the loops. Thus, list comprehension is much more efficient than the append() function of the lists.</p> <p>The * operator has shown the best performance out of all the four methods.</p> <hr></100000:>

Putem vedea că buclele for și while durează aproape același timp de execuție. Cu toate acestea, bucla for este puțin mai bună decât bucla while.

Înțelegerea listelor arată performanțe mult mai bune decât buclele for și while. Este de 2-3 ori mai rapid decât buclele. Astfel, înțelegerea listelor este mult mai eficientă decât funcția append() a listelor.

Operatorul * a arătat cea mai bună performanță dintre toate cele patru metode.

șir de caractere java conține