Holla Tech - Learn

List Functions
 

Another way of altering lists is using the append method. This adds an item to the end of an existing list. 

nums = [1, 2, 3]
nums.append(4)
print(nums

 

Result: 

>>
[1, 2, 3, 4] >>> 

 

NOTE!
The dot before append is there because it is a method of the list class. Methods will be explained in a later lesson.

List Functions
 

To get the number of items in a list, you can use the len function.

nums = [1, 3, 5, 2, 4]
print(len(nums)) 

 

Result: 

>>
5
>>> 

 

NOTE!
Unlike append, len is a normal function, rather than a method. This means it is written before the list it is being called on, without a dot.

List Functions
 

The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.

words = [“Python”, “fun”]
index = 1
words.insert(index, “is”)
print(words

 

Result: 

>>
[‘Python’, ‘is’, ‘fun’] >>> 

 


List Functions
 

The index method finds the first occurrence of a list item and returns its index.
If the item isn’t in the list, it raises a ValueError.

letters = [‘p’, ‘q’, ‘r’, ‘s’, ‘p’, ‘u’]
print(letters.index(‘r’))
print(letters.index(‘p’))
print(letters.index(‘z’)) 

 

Result: 

>>
2
0
ValueError: ‘z’ is not in list
>>> 

 

NOTE!
There are a few more useful functions and methods for lists. max(list): Returns the list item with the maximum value min(list): Returns the list item with minimum value list.count(obj): Returns a count of how many times an item occurs in a list list.remove(obj): Removes an object from a list list.reverse(): Reverses objects in a list

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE PYTHON MAIN COURSE PAGE. 

PYTHON MAIN COURSE PAGE

 


©️ License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT