You are on page 1of 10

ASN Senior Secondary School

Artificial Intelligence
Python List
Session-2
Python List
• Python has a lot of list methods that allow us
to work with lists. Like
– Append
– Extend
– Insert
– Remove
– Count
– Pop
append()
• The append() method adds an item to the end
of the list.
– # animals list
• animals = ['cat', 'dog', 'rabbit']
– # 'guinea pig' is appended to the animals
• animals.append('guinea pig')
– # Updated animals
• print('Updated animals list: ', animals)
extend()
• The extend() extends the list by adding all
items of a list (passed as an argument) to the
end.
– # language list
• language = ['French', 'English', 'German']
– # another list of language
• language1 = ['Spanish', 'Portuguese']
• language.extend(language1)
– # Extended List
• print('Language List: ', language)
insert()
• The insert() method inserts an element to the list
at a given index.
– insert() Parameters
• The insert() function takes two parameters:
• index - position where an element needs to be inserted
• element - this is the element to be inserted in the list
• # vowel list
– vowel = ['a', 'e', 'i', 'u']
• # inserting element to list at 4th position
– vowel.insert(3, 'o')
– print('Updated List: ', vowel)
remove()
• The remove() method removes the first
matching element (which is passed as an
argument) from the list.
– # animals list
• animals = ['cat', 'dog', 'rabbit', 'guinea pig']
– # 'rabbit' is removed
• animals.remove('rabbit')
– # Updated animals List
• print('Updated animals list: ', animals)
count()
• The count() method returns the number of
occurrences of an element in a list.
– # vowels list
• vowels = ['a', 'e', 'i', 'o', 'i', 'u']
– # count element 'i‘
• count = vowels.count('i')
– # print count
• print('The count of i is:', count)
– # count element 'p‘
• count = vowels.count('p')
– # print count
• print('The count of p is:', count)
pop()
• The pop() method removes the item at the
given index from the list and returns the
removed item.
– # programming languages list
• languages = ['Python', 'Java', 'C++', 'French', 'C']
– # remove and return the 4th item
• return_value = languages.pop(3)
• print('Return Value:', return_value)
– # Updated List
• print('Updated List:', languages)
reverse()
• The reverse() method reverses the elements
of a given list.
– # Operating System List
• os = ['Windows', 'macOS', 'Linux']
• print('Original List:', os)
– # List Reverse
• os.reverse()
– # updated list
• print('Updated List:', os)
sort()
• The sort() method sorts the elements of a
given list.
– # vowels list
• vowels = ['e', 'a', 'u', 'o', 'i']
– # sort the vowels
• vowels.sort()
– # print vowels
• print('Sorted list:', vowels)

You might also like