reverse elements in a list;
x = [1,2,3]
x.reverse()
x
[3,2,1]
This reverses the list but doesn't return anything.
Tuesday, 22 March 2011
Remove
removes 1st occurance of a value in a list;
x = ['to', 'be', 'or', 'not', 'to', 'be']
x.remove('be')
x
['to', 'or', 'not','to', 'be' ]
x = ['to', 'be', 'or', 'not', 'to', 'be']
x.remove('be')
x
['to', 'or', 'not','to', 'be' ]
Pop
x= [1,2,3,]
x.pop()
3
Deletes the last entry of the list
x
[1,2]
x.pop(0) - specifies which item to delete
1 - returns the value of the item it just deleted
x
[2]
x.pop()
3
Deletes the last entry of the list
x
[1,2]
x.pop(0) - specifies which item to delete
1 - returns the value of the item it just deleted
x
[2]
Insert
insert an object into specified position in a list:
numbers [1,2,3,4,,5,6]
numbers.insert(3,'four') - insert 'four' at position 3
number
[1,2,3,'four',5,6,7]
numbers [1,2,3,4,,5,6]
numbers.insert(3,'four') - insert 'four' at position 3
number
[1,2,3,'four',5,6,7]
Index
Knights = ['Richard', 'of ', 'York', 'Gave', 'Battle', 'in', 'vein']
Knights.index('York')
2
Knights.index('pudding')
-error
Finds the word in the list and returns its position.
Knights.index('York')
2
Knights.index('pudding')
-error
Finds the word in the list and returns its position.
Count
['to','be','or','not','to','be'].count ('to')
2
This counts the amount of times a given object appears in the list (in this case the word 'to')
2
This counts the amount of times a given object appears in the list (in this case the word 'to')
Extend
append several items at once:
a = [1,2,3]
b = [4,5,6]
a.extend(b)
a
[1,2,3,4,5,6]
This is similar to concatenation except the variable 'a' is modified. In concatenation, the result would create a new variable.
a = [1,2,3]
b = [4,5,6]
a.extend(b)
a
[1,2,3,4,5,6]
This is similar to concatenation except the variable 'a' is modified. In concatenation, the result would create a new variable.
Subscribe to:
Posts (Atom)