logo

Python'da Liste Nasıl Başlatılır?

Herhangi bir Python nesnesi, bir Python Listesindeki sıralı değerler grubunda bulunabilir. Liste Python'da değiştirilebilir bir veri yapısı olduğundan, bu kapsayıcıdaki mevcut değerleri ekleyebilir, kaldırabilir veya değiştirebiliriz. Kümelerin aksine, liste aynı değerin çok sayıda örneğine izin verir ve her birini farklı bir öğe olarak ele alır. Bu derste Python'da bir liste nesnesinin nasıl başlatılacağını öğreneceğiz.

Listeleri Köşeli Parantezleri Kullanarak Başlatın

Python'da değerleri olmayan boş bir liste oluşturmak istiyorsak, köşeli parantez kullanmak, değerleri olmayan bir listeyi başlatmanın bir yoludur. Bir listeyi başlatmak için yalnızca öğe değerleri olan veya olmayan bir çift köşeli parantez belirtmemiz gerekir.

java rastgele sayı

Kod

 # 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_) 

Çıktı:

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

Bir Listeyi Başlatmak için Yerleşik list() İşlevini Kullanma

Python'un list() işlevi yinelenebilir bir nesne olan listeyi oluşturur. Dolayısıyla bu kodlama dilinde herhangi bir veri olmadan boş bir Python listesi oluşturmanın başka bir yoludur.

Bir yineleyici nesne, yinelemeyi mümkün kılan bir dizi veya bir kapsayıcının tümü yinelenebilir olabilir. Herhangi bir girdi verilmediği takdirde yeni bir boş liste oluşturulur.

Kod

 # 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_) 

Çıktı:

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

Köşeli parantez yöntemi, daha açık ve daha açıklayıcı olduğundan yerleşik list() işlevine göre tercih edilir.

Bir Listeyi Başlatmak için Liste Anlamlarını Kullanma

Listenin varsayılan parametrelerini ayarlamak için liste anlama yaklaşımını kullanabiliriz. Köşeli parantez içine alınmış bir ifadeden, bir for ifadesinden ve ardından gelebilecek veya gelmeyebilecek isteğe bağlı bir if ifadesinden oluşur. Listeye eklemek istediğimiz herhangi bir öğe ifade olarak yazılabilir. Kullanıcı listeyi sıfırlarla başlatırsa ifade 0 olur.

Liste kavrama, yineleyiciye dayanan bir liste oluşturmaya yönelik zarif, basit ve iyi bilinen bir yaklaşımdır.

Kod

 # 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_) 

Çıktı:

i d e'nin tam biçimi
 The list was created using list comprehension: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Bu teknik, listeleri Python'un for ve while döngülerinden çok daha hızlı başlatır.

* Operatörünü Kullanarak Python Listesini Başlatın

Python'da bir listeyi başlatmanın başka bir yolu da * operatörünü kullanmaktır. Birden fazla değere sahip bir liste oluşturur. Bu operatörü kullanmanın sözdizimi şöyledir: [element] * n. Burada n, listedeki öğeyi kaç kez tekrarlamak istediğimizi gösterir.

yoksa Java

Bu yöntem, önceden tanımlanmış uzunlukların bir listesini başlatmak istediğimizde yardımcı olur.

Kod

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

Çıktı:

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

Bu yöntem çok etkili ve liste oluşturmanın en hızlı yoludur. Bu eğitimin ilerleyen kısımlarında yöntemlerin harcadığı süreyi karşılaştıracağız.

Bir Python listesini başlatmak için bu operatörü kullanmanın tek dezavantajı, bir 2B liste oluşturmamız gerektiği zamandır, çünkü bu yöntem yalnızca sığ bir liste oluşturacaktır, yani tek bir liste nesnesi oluşturacaktır ve tüm dizinler buna atıfta bulunacaktır. çok sakıncalı olacak bir nesne. Bu nedenle 2 boyutlu listeler oluşturmamız gerektiğinde liste kavramayı kullanırız.

Bir for Döngüsü ve ekleme() kullanma

Boş bir liste oluşturacağız ve listenin apend() fonksiyonunu kullanarak öğe eklemek için bir for döngüsü çalıştıracağız.

Kod

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

Bir Listeyi Başlatmak için While Döngüsü Kullanma

Bir listeyi başlatmak için tıpkı for döngüsünde kullandığımız gibi while döngüsünü de kullanabiliriz.

Kod

 # 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):>

Zaman Karmaşıklığı

Şimdi açıklanan yaklaşımların her birinin ne kadar süreceğini görelim. 100000 öğeden oluşan bir listeyi 1000 kez başlatacağız. Her yöntemin bu görevi gerçekleştirmek için harcadığı ortalama süreyi hesaplayacağız.

karşılaştırılabilir java

Kod

 # 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:>

For ve while döngülerinin neredeyse aynı yürütme süresini aldığını görebiliriz. Ancak for döngüsü while döngüsünden biraz daha iyidir.

Liste kavrama, for ve while döngülerinden çok daha iyi performans gösterir. Döngülere göre 2-3 kat daha hızlıdır. Bu nedenle listenin anlaşılması, listelerin Append() işlevinden çok daha verimlidir.

* operatörü dört yöntem arasında en iyi performansı göstermiştir.