Unleash Your Potential - Namagunga Girls Coding Club
Python Lists Guide - Everything You Need to Know
1. Lists in Python3
By Lakshmi Sarvani Videla
NOTE: all the contents in this ppt are taken from w3schools
https://www.w3schools.com/python/python_lists.asp
2. Python Collections (Arrays)
There are four collection data types in the Python programming language:
•List is a collection which is ordered and changeable. Allows
duplicate members.
•Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
•Set is a collection which is unordered and unindexed. No
duplicate members.
•Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
3. List
A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.
Create a List:
Example
thislist = ["apple", "banana", "cherry"]
print(thislist)
The list() Constructor
It is also possible to use the list() constructor to make a list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
4. You access the list items by referring to the index
number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
print(thislist[-1])
5. +” operator :- This operator is used to concatenate two lists into a single list.
“*” operator :- This operator is used to multiply the list “n” times and return the
single list.
lis = [1, 2, 3]
lis1 = [4, 5, 6]
lis2= lis + lis1
lis3 = lis * 3
print(lis2)
print(lis3)
Output:
list after concatenation is : 1 2 3 4 5 6
list after combining is : 1 2 3 1 2 3 1 2 3
6. min() :- This function returns the minimum element of list.
max() :- This function returns the maximum element of list.
lis = [2, 1, 3, 5, 4]
print ("The length of list is : ", len(lis))
# using min() to print minimum element of list
print ("The minimum element of list is : ", min(lis))
# using max() to print maximum element of list
print ("The maximum element of list is : ", max(lis))
7. Change Item Value
To change the value of a specific item, refer to
the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
8. Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
9. Check if Item Exists
To determine if a specified item is present in a list use the
in keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
10. List Length
To determine how many items a list have, use the len()
method:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
11. Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
To add an item at the specified index, use the insert() method:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
12. The extend() method adds the specified list elements (or any iterable) to the end of
the current list.
Syntax
list.extend(iterable)
iterable Required. Any iterable (list, set, tuple, etc.)
Example Add the elements of cars to the fruits list:
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
Example Add a tuple to the fruits list:
fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.extend(points)
13. Remove Item
There are several methods to remove items from a list:
1. The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
2. The pop() method removes the specified index, (or the last item if index is not
specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
14. The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till
‘b’ mentioned in arguments.
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
15. The copy() method returns a copy of the specified list.
Example
Copy the fruits list:
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
16. The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting criteria(s). Syntax
list.sort(reverse=True|False, key=myFunc)
Example
Sort the list alphabetically:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Example
Sort the list descending:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
17. Sort() Sort the list by the length of the values:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
Example: Sort the list by the length of the values and reversed:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
18. The reverse() method reverses the sorting order
of the elements.
Example
Reverse the order of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
The built-in function reversed() returns a
reversed iterator object. The buil-in
function reversed() returns a reversed iterator object.
19. The count() method returns the number of elements with the specified value.
Return the number of times the value "cherry" appears int the fruits list:
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
index(ele, beg, end) :- This function returns the index of first occurrence of element after beg and before
end.
lis = [2, 1, 3, 5, 4, 3]
print ("The first occurrence of 3 after 3rd position is : ", lis.index(3, 3, 6))
print ("The number of occurrences of 3 is : ", end="")
print (lis.count(3))
Output:
The first occurrence of 3 after 3rd position is : 5
The number of occurrences of 3 is : 2
20. Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
count() Returns the number of elements with the specified value
index() Returns the index of the first element with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current
list
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
21. Reading list / array elements from user
a=input()
b= []
for x in a.split():
b.append(int(x))
(or)
a=input()
b = [int(x) for x in a.split()]
22. # sort the characters in a particular word
a=input()
b=list(a)
b.sort()
print(b)
grades = ['A','B','F','A+','O','F','F']
def remove_fails(grade):
return grade ! = 'F'
ans=list(filter(remove_fails,grades))
print(ans)
23. from random import shuffle
def jumble(word):
anagram=list(word) #converting a string into list ..here each character is a list item
shuffle(anagram)
return ''.join(anagram) # converting list back into string…we cannot use str(anagram) as it will convert as “[‘o’,’e’….]”
words =['beetroot','carrots','potatoes']
'''anagrams=[]
for word in words:
anagrams.append(jumble(word))
print(anagrams)'''
'''ans=[jumble(word) for word in words]
print(ans)'''
ans=list(map(jumble,words))
print(ans)