Wednesday, 20 February 2019

python lists

letters = ['a', 'b', 'c']
matrix = [[0, 1], [2, 3]]

zeros = [0]*5
combined = zeros + letters
print(combined)

[0, 0, 0, 0, 0, 'a', 'b', 'c']

print(list(range(10)))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list('hello world'))

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

print(len(list('hello world')))

11

letters = ['a', 'b', 'c']
print(letters[-1])

c

letters = ['a', 'b', 'c']
print(letters[0:2])

['a', 'b']

letters = ['a', 'b', 'c', 'd', 'e', 'f']
print(letters[::2])

['a', 'c', 'e']

letters = ['a', 'b', 'c', 'd', 'e', 'f']
print(letters[1::2])

['b', 'd', 'f']

letters = ['a', 'b', 'c', 'd', 'e', 'f']
print(letters[::-2])

['f', 'd', 'b']

letters = ['a', 'b', 'c']
first, second, third = letters
print(first, second, third)

a b c

letters = ['a', 'b', 'c', 'd', 'e', 'f']
first, second, *other = letters
print(first, other)

a ['c', 'd', 'e', 'f']

letters = ['a', 'b', 'c', 'd', 'e', 'f']
first, *other, last = letters
print(first, other, last)

a ['b', 'c', 'd', 'e'] f

letters = ['a', 'b', 'c']
for letter in enumerate(letters):
    print(letter)

(0, 'a')
(1, 'b')
(2, 'c')

letters = ['a', 'b', 'c']
for letter in enumerate(letters):
    print(letter[0], letter[1])

0 a
1 b
2 c

letters = ['a', 'b', 'c']
for index, letter in enumerate(letters):
    print(index, letter)

0 a
1 b
2 c

letters = ['a', 'b', 'c']
letters.append('d')
letters.insert(1, '-')
print(letters)

['a', '-', 'b', 'c', 'd']

letters = ['a', 'b', 'c', 'd']
letters.pop()
print(letters)

['a', 'b', 'c']

letters = ['a', 'b', 'c', 'd']
letters.pop(1)
print(letters)

['a', 'c', 'd']

letters = ['a', 'b', 'c', 'd']
letters.remove('c')
print(letters)

['a', 'b', 'd']

letters = ['a', 'b', 'c', 'd']
del letters[1:3]
print(letters)

['a', 'd']

letters = ['a', 'b', 'c', 'd']
letters.clear()
print(letters)

[]

letters = ['a', 'b', 'c', 'd']
print(letters.index('c'))

2

letters = ['a', 'b', 'c', 'b', 'd']
if 'b' in letters:
    print(letters.count('b'))

2

numbers = [3,2,1,4,5]
numbers2 = numbers.copy()
numbers2.sort()
numbers2.reverse()
print(numbers2)

[5, 4, 3, 2, 1]

numbers = [2,2,4,6,3,4,6,1]
uniques = []
for number in numbers:
    if number not in uniques:
        uniques.append(number)
print(uniques)

[2, 4, 6, 3, 1]

reference:
https://www.youtube.com/watch?v=9OeznAkyQz4

No comments:

Post a Comment