lst = [1,2,3,]
lst.append(4)
lst
[1,2,3,4]
Simply adds the value in the brackets to the variable (note the variable was declared 'lst' and not 'list'. 'list' is a function and would have given an error).
Tuesday, 22 March 2011
Remove elements
numbers = [1,2,3,4,5,]
numbers [1,4] = []
numbers = [1,5]
This has similar effect to the delete statement and is related to replace. In this case you are simply replacing all the elements from position 1 up to (but not including) position 4 and replacing it with [] - an empty list. The items that survive in the list are those in position [0,4].
numbers [1,4] = []
numbers = [1,5]
This has similar effect to the delete statement and is related to replace. In this case you are simply replacing all the elements from position 1 up to (but not including) position 4 and replacing it with [] - an empty list. The items that survive in the list are those in position [0,4].
Insert elements
numbers = [1,5]
numbers [1:1] = [2,3,4]
numbers
[1,2,3,4,5,]
The inserted elements are placed in the list at position 1
numbers [1:1] = [2,3,4]
numbers
[1,2,3,4,5,]
The inserted elements are placed in the list at position 1
List statement, assign to slices
name = list('Pearl')
name
['P','e','a,'r','l'']
name[2:] = list('ar')
name
['P','e','a','r']
List statement turned the string ('Pearl') into a list.
The list('ar') replaces anything from position 2 onwards in the name list, hence it's new value being ['P','e','a','r']
name
['P','e','a,'r','l'']
name[2:] = list('ar')
name
['P','e','a','r']
List statement turned the string ('Pearl') into a list.
The list('ar') replaces anything from position 2 onwards in the name list, hence it's new value being ['P','e','a','r']
Deletion
names = ['Alice', 'Beth', 'Julie', 'Cecil', 'Gary']
del names [2]
names
['Alice', 'Beth', 'Cecil', 'Gary']
Use the del function to delete item from list.
del names [2]
names
['Alice', 'Beth', 'Cecil', 'Gary']
Use the del function to delete item from list.
Changing Lists
- assignment:
x = [1,1,1] - Declare list and its values
x[1] = 2 - Assign value of 2 to position 1
x
[1,2,1,] - New value of x
To change list items, index the item you want to change (x[1]) and assign a new value to it (x[1] =2).
x = [1,1,1] - Declare list and its values
x[1] = 2 - Assign value of 2 to position 1
x
[1,2,1,] - New value of x
To change list items, index the item you want to change (x[1]) and assign a new value to it (x[1] =2).
Len Min/Max
example:
numbers = [100, 34, 678]
len(numbers)
3
max(numbers)
678
min(numbers)
34
max(2,3)
3
min(2,3)
Len function returns either the highest or lowest values in a sequence (the first two examples) or directly as a sequence argument (the last two examples).
numbers = [100, 34, 678]
len(numbers)
3
max(numbers)
678
min(numbers)
34
max(2,3)
3
min(2,3)
Len function returns either the highest or lowest values in a sequence (the first two examples) or directly as a sequence argument (the last two examples).
Subscribe to:
Posts (Atom)