Python Lists: Contents
Python Lists: Contents
Contents:
1.Introduction
1.1)Python datatypes
1.2)List creation
2.List Methods
2.1)Access Items
2.2)Change Item Value
2.3)Remove Item
2.4)Check if Item Exists
2.5)List Length
2.6)Add Items
2.7)Join Two Lists
2.8)Copy a list
2.9)Reversing a list
2.10)Sorting a list
2.11)Index of a element in list
2.12)Counting number of occurances of a element in list
2.13)Max and min elements in a list
3.List comprehensions
3.1)List Comprehensions with Conditionals
3.2)Nested List Comprehensions
1.Introduction
Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data.
Lists are one of the datatype of python.
They are just like the arrays, declared in other languages. A single list may contain
DataTypes like Integers, Strings, as well as Objects. The elements in a list are separated by
comma , .Lists can be modified.Each element in the list has its definite place in the list,
which allows duplicating of elements in the list.
In Python lists are written with square brackets [ ] and we have forward indexing and
backward indexing.
Example as fallows:
#List with no elements :
list1 = [ ]
print(list1)
Access Items:
Positive indexing:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output::banana
Negative indexing:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Output:: cherry
Range of Indexes(Slicing):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])
This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output:: ['orange', 'kiwi', 'melon']
Remove Item:
The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output:: ['apple', 'cherry']
The pop() method removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Output:: ['apple', 'banana']
#No Output
List Length:
To determine how many items a list has, use the len() function:
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output:: 3
Add Items:
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:: ['apple', 'banana', 'cherry', 'orange']
We can use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output:: ['a', 'b', 'c', 1, 2, 3]
Copy a list:
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference
to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output:: ['apple', 'banana', 'cherry']
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Output:: ['apple', 'banana', 'cherry']
Reversing a list:
Reverse the order of the fruit list using reverse():
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
Output:: ['cherry', 'banana', 'apple']
Sorting a list:
The sort() method sorts the list ascending by default.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
Output:: ['BMW', 'Ford', 'Volvo']
3.List comprehensions
Note that you can rewrite the above code with a Python for loop easily as fallows,
list = []
for x in range(10)
if x % 2 == 0:
list.append(x)
print(list)
Output:: [0, 2, 4, 6, 8]
Multiple If Conditions:
Now that you have understood how you can add conditions, it's time to convert the
following for loop to a list comprehension with conditionals.
list= []
for x in range(100):
if x%2 == 0 :
if x%6 == 0:
list.append(x)
print(list)
Output:: [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]
If-Else Conditions:
Of course, it's much more common to work with conditionals that involve more than one
condition. That's right, you'll more often see if in combination with elif and else. Now, how
do you deal with that if you plan to rewrite your code?
Take a look at the following example of such a more complex conditional in a for loop:
list= [x+1 if x >= 20 else x+5 for x in range(20)]
print(list)
Output:: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24]
Now look at the following code chunk, which is a rewrite of the above piece of code:
for x in range(20):
if x >= 20:
print(x+1)
else:
print(x+5)
Output:: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24]
list_of_list = [[1,2,3],[4,5,6],[7,8]]
list = [y for x in list_of_list for y in x]
print(list)
output:: [1, 2, 3, 4, 5, 6, 7, 8]
Let's now consider another example, where you see that you can also use two pairs of
square brackets to change the logic of your nested list comprehension:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
list = [[row[i] for row in matrix] for i in range(3)]
print(list)
output:: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
You can rewrite the code chunk above to a nested for loop as fallows,
matrix = [[1,2,3],[4,5,6],[7,8,9]]
transposed = []
for i in range(3):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
output:: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]