is
help
и dir
["Foo", [baba, 8, []], "Baz"]
>>> words = ["Foo", "Bar", "Baz", "Qux"]
>>> primes = [2, 3, 5, 7, 11, 13, 17, 19]
>>> asl = [21, "Male", "Sofia"]
>>> dish = ["spam", "bacon", "sausage", "spam"]
>>> actor = "Eric Idle"
>>> sketch = "Spam"
>>> stuff = [actor, 42, sketch]
>>> print(stuff)
['Eric Idle', 42, 'Spam']
>>> stuff[1] = stuff
>>> print(stuff)
['Eric Idle', [...], 'spam']
>>> stuff[1][0] = 2 ** 9
>>> print(stuff)
[512, [...], 'Spam']
len(списък)
>>> len(["Foo", "Bar", "Baz", "Qux"])
4
+
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
in
>>> "Spam" in ["Eggs", "Bacon", "Spam"]
True
not in
>>> "Spam" not in ["Eggs", "Bacon", "Spam"]
False
>>> cheese = ['Red Leicester', 'Cheddar', 'Emmental', 'Mozzarella', 'Tilsit', 'Limburger']
>>> cheese[0]
'Red Leicester'
>>> cheese[-1]
'Limburger'
>>> cheese[1:4]
['Cheddar', 'Emmental', 'Mozzarella']
>>> cheese[1:-1]
['Cheddar', 'Emmental', 'Mozzarella', 'Tilsit']
>>> cheese[1:]
['Cheddar', 'Emmental', 'Mozzarella', 'Tilsit', 'Limburger']
>>> cheese[:3]
['Red Leicester', 'Cheddar', 'Emmental']
>>> cheese[0:6:2]
['Red Leicester', 'Emmental', 'Tilsit']
>>> cheese[::2]
['Red Leicester', 'Emmental', 'Tilsit']
>>> cheese[::-1]
['Limburger', 'Tilsit', 'Mozzarella', 'Emmental', 'Cheddar', 'Red Leicester']
>>> food = ['eggs', 'bacon', 'spam']
>>> print(food)
['eggs', 'bacon', 'spam']
>>> food[1] = 'sausage'
>>> print(food)
['eggs', 'sausage', 'spam']
>>> food.append('spam')
>>> print(food)
['eggs', 'sausage', 'spam', 'spam']
>>> food.append(['манджа', 'грозде'])
>>> print(food)
['eggs', 'sausage', 'spam', 'spam', ['манджа', 'грозде']]
>>> food = ['ham', 'eggs']
>>> food.extend(['bacon', 'spam'])
>>> print(food)
['ham', 'eggs', 'bacon', 'spam']
>>> del food[1]
>>> print(food)
['ham', 'bacon', 'spam']
>>> food[:2] = ['I', 'want', 'more']
>>> print(food)
['I', 'want', 'more', 'spam']
>>> del food[:3]
>>> print(food)
['spam']
>>> knights = ["Arthur", "Galahad"]
>>> knights.append('Bedevere')
>>> knights
['Arthur', 'Galahad', 'Bedevere']
>>> knights.extend(['Lancelot', 'Robin']) # Може и knigts += ['Lancelot', 'Robin']
>>> knights
['Arthur', 'Galahad', 'Bedevere', 'Lancelot', 'Robin']
>>> knights.sort()
>>> knights
['Arthur', 'Bedevere', 'Galahad', 'Lancelot', 'Robin']
>>> knights.reverse()
>>> knights
['Robin', 'Lancelot', 'Galahad', 'Bedevere', 'Arthur']
>>> someone = knights.pop()
>>> print(someone, knights)
Arthur ['Robin', 'Lancelot', 'Galahad', 'Bedevere']
>>> someone = knights.pop(2)
>>> print(someone, knights)
Galahad ['Robin', 'Lancelot', 'Bedevere']
>>> food = ['spam', 'eggs', 'sausage', 'spam', 'bacon', 'spam']
>>> food.index('eggs')
1
>>> food.index('hamandeggs')
ValueError: list.index(x): x not in list
>>> food.index('spam', 1)
3
>>> food.index('spam', 1, 3)
ValueError: list.index(x): x not in list
>>> food.count('spam')
3
>>> food.count('bacon')
1
>>> food = ['spam', 'eggs', 'sausage', 'spam', 'bacon', 'spam']
>>> food.insert(2, 'spam')
>>> food
['spam', 'eggs', 'spam', 'sausage', 'spam', 'bacon', 'spam']
>>> food.remove('spam')
>>> food
['eggs', 'spam', 'sausage', 'spam', 'bacon', 'spam']
>>> food.remove('spam')
>>> food
['eggs', 'sausage', 'spam', 'bacon', 'spam']
>>> food.remove('zzz')
ValueError: list.remove(x): x not in list
>>> ['eggs', 'sausage'] * 3
['eggs', 'sausage', 'eggs', 'sausage', 'eggs', 'sausage']
for
for 〈име〉 in 〈нещо-за-обхождане〉:
〈блок код〉
in
е част от синтаксиса, не проверка за притежание〈нещо-за-обхождане〉
може да е както литерал —[1, 2, 3]
така и име, например knights
break
излиза от цикълаcontinue
прекъсва текущата итерация и продължава изпълнението на цикъла от следващия елемент
>>> numbers = [1, 2, 3, 5, 7, 11, 13]
>>> answer = 0
>>>
>>> for n in numbers:
answer += n
print("Adding {0} to the answer".format(n))
>>> print(answer)
42
for n in range(0, 20):
if n % 2: continue
print(n)
if n > 9: break
Произвежда следния резултат:
0
2
4
6
8
10
В python оператора =
дава ново име на съществуващ обект.
Последния не се копира.
>>> spam = ['Lancelot', 'Arthur']
>>> eggs = spam
>>> eggs[1] = 'Bedevere'
>>> spam
['Lancelot', 'Bedevere']
В python нищото е None
.
>>> print(None)
None
>>> 1 is None
False
>>> if not None:
print('None is treated as "False"')
None is treated as "False"
primes = (2, 3, 5, 7, 11, 13)
primes = 2, 3, 5, 7, 11, 13
prime = (2,)
, иначе ще се сметне за израза 2
>>> primes[0]
2
>>> primes[1:4]
(3, 5, 7)
>>> primes[5] = 17
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
("Foo", "Bar", ("Spam",), ("More", "Spam"))
+
*
1 in (1, 2)
for x in (1, 2):
.index
.count
>>> (a, b) = 1, 2
>>> print(a)
1
>>> a, b = 1, 2
>>> a, b = b, a
>>> print(a)
2
>>> print(b)
1
>>> numbers = (1, 2, 3)
>>> a, b, c = numbers
>>> numbers = [1, 2, 3]
>>> [a, b, c] = numbers
Списъците/n-торките се сравняват лексигокрафски
>>> (1, 2) < (1, 3)
True
>>> (1, 2) < (1, 2)
False
>>> (1, 2) < (1, 2, 3)
True
>>> [1, 2] < [1, 3]
True
>>> (1, 2) < [1, 3] # tuple vs. list
TypeError: unorderable types: tuple() < list()
set([списък/n-торка])
или {елементи (поне 1), разделени с ","}
>>> numbers = {1, 2, 3, 8, 2}
>>> numbers
{8, 1, 2, 3}
>>> 2 in numbers
True
>>> 4 in numbers
False
>>> numbers.add(4)
>>> 4 in numbers
True
>>> numbers.remove(1)
>>> numbers
{8, 2, 3, 4}
>>> {1, 2, 3} | {2, 3, 4}
{1, 2, 3, 4}
>>> {1, 2, 3} & {2, 3, 4}
{2, 3}
>>> {1, 2, 3} - {2, 3, 4}
{1}
>>> {1, 2, 3} ^ {2, 3, 4}
{1, 4}
>>> {1, 2, 3} < {2, 3, 4}
False
>>> {2, 3} < {2, 3, 4} # < - подмножество
True
>>> {2, 3} == {2.0, 3}
True
>>> {1, 2}.isdisjoint({3, 4})
True
>>> set([1, 2, 3, 8, 2])
{8, 1, 2, 3}
>>> list({1, 2, 3})
[1, 2, 3]
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> list((1, 2, 3))
[1, 2, 3]
>>> languages = {
'Spain': 'Spanish',
'Great Britain': 'English',
'Italy': 'Italian',
'Mexico': 'Spanish',
'France': 'French',
'USA': 'English',
}
>>> languages['Mexico']
'Spanish'
>>> capitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Brazil': 'Rio de Janeiro',
'Malaysia': 'Kuala Lumpur',
}
>>> capitals['Brazil']
'Rio de Janeiro'
>>> capitals['Brazil'] = 'Brazil'
>>> capitals['Brazil']
'Brazil'
>>> capitals['Sweden'] = 'Stockholm'
>>> capitals['Sweden']
'Stockholm'
>>> del capitals['Malaysia']
>>> capitals['Malaysia']
KeyError: 'Malaysia'
>>> capitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Brazil': 'Rio de Janeiro',
'Sweden': 'Stockholm',
}
>>> capitals.get('Assyria')
None
>>> capitals.get('Assyria', "I don't know")
"I don't know"
>>> 'Sweden' in capitals
True
>>> list(capitals.keys())
['Brazil', 'Sweden', 'Germany', 'France']
>>> list(capitals.values())
['Rio de Janeiro', 'Stockholm', 'Berlin', 'Paris']
>>> len(capitals)
4
>>> numbers = {
"One": "I",
"Two": "II",
}
>>> list(numbers.items())
[('One', 'I'), ('Two', 'II')]
>>> numbers.update({"Three": "III", "Four": "IV"})
>>> numbers
{'Four': 'IV', 'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> numbers.pop('Four')
'IV'
>>> numbers
{'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> {1: 1, 2:2} == {2: 2, 1: 1}
True
>>> numbers = {
"One": "I",
"Two": "II",
}
>>> numbers_copy = numbers.copy()
>>> numbers_copy
{'Two': 'II', 'One': 'I'}
>>> numbers
{'Two': 'II', 'One': 'I'}
>>> numbers.clear()
>>> numbers_copy
{'Two': 'II', 'One': 'I'}
>>> numbers
{}
>>> dict(france="Paris", italy="Rome")
{'italy': 'Rome', 'france': 'Paris'}
>>> dict([('One', 'I'), ('Two', 'II')])
{'Two': 'II', 'One': 'I'}
>>> dict.fromkeys([1, 2, 3], 'Unknown')
{1: 'Unknown', 2: 'Unknown', 3: 'Unknown'}
hash(s) == s[0]*31(n-1)+s[1]*31(n-2)+...+s[n-1]
hash("abc") → 66498
hash("d") → 68