Zum Inhalt

Listen

Liste [ ]

Sie sind Container rund um Daten
Eine Liste ist eine geordnete Folge von Objekten, die von beliebigem Typ sein können
Jede Sammlung von Artikeln []

Listen sind eine Form von Arrays. Listen sind veränderbar

li = [1, "a", 2, 'b', 2.5, True]

amazon_cart = [
    'notebooks',
    'sunglasses',
    'toys',
    'grapes']

print(amazon_cart[1])          # Indexing the list
print(amazon_cart[0::2])       # Slicing in list
amazon_cart[0] = 'laptop'      # lists are mutable[replaceable], modifies the list
print(amazon_cart)

new_cart = amazon_cart.copy()
new_cart = amazon_cart[:]     # [:] Creating a new copy or .copy()
Matrix

Eine Matrix ist eine Möglichkeit, zweidimensionale Listen oder mehrdimensionale Listen oder Arrays zu beschreiben.
Wird hauptsächlich für maschinelles Lernen verwendet.

matrix = [
    [1, 5, 2],
    [0, 1, [4]],
    [3, 7, 9],
]
print(matrix[1][2])         # Outpu: [4]
Methoden für Listen/Arrays
basket = [1, 2, 3, 4, 5]

Einzigartige Werte

print(set(basket))          # Removes Duplicates[returns unique values]
Methoden hinzufügen
basket.append(100)          # adding at the last
print(basket)

basket.insert(4, 100)       # inserting through index
print(basket)

basket.extend([100])        # extends the list and is iterable
print(basket)
Methoden entfernen
basket.pop()        # pops off end of the list
basket.pop(4)       # removes through index
print(basket)

basket.remove(100)  # remove the value given
print(basket)

basket.clear()      # completely clears the list
print(basket)
letter = ['a', 'b', 'c', 'd', 'e', 'a']


print(letter.count('a'))    # counts how many times value occurs in the list[through index or value]

print(letter.index('b'))    # looks for the value and returns their index number

letter.sort()               # sorts the list in an order
print(letter)

print(sorted(basket))       # works the same but produces a new list not modifies it

letter.reverse()            # reverse the list
print(letter)               # Output: ['a', 'a', 'b', 'c', 'd', 'e'] returns the original one

Diese Version erstellt eine neue Liste, die Sie zum Umkehren verwenden. [zum Kopieren von [:]]

print(letter[::-1])

Um zu wissen, ob ein Wert in den Daten vorhanden ist oder nicht [kann in Zeichenfolgen usw. verwendet werden]

print('x' in letter)
print("i" in 'Hi, I am Marwa')  # in keyword for strings
Tricks in der Liste
print(list(range(101)))   # Output: gives the range from 0 to 100

sentence = " ".join(['hi', 'my', 'name', 'is', 'marwa'])  # joins a list
print(sentence)
Liste auspacken
a, b, c, *other, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(a)
print(b)
print(c)
print(other)
print(d)