Python List Concept
Python List Concept
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
OUTPUT:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc.
Example
Print the last item of the list:
OUTPUT:
Cherry
When specifying a range, the return value will be a new list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
OUTPUT:
Note: The search will start at index 2 (included) and end at index 5
(not included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to "orange":
OUTPUT:
By leaving out the end value, the range will go on to the end of the
list:
Example
This example returns the items from "cherry" and to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
OUTPUT:
Example
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:
Example
Change the second item:
OUTPUT:
Example
Print all items in the list, one by one:
OUTPUT:
apple
banana
cherry
You will learn more about for loops in our Python For Loops Chapter.
if value in L:
print "list contains", value
To get the index of the first matching item, use index:
i = L.index(value)
The index method does a linear search, and stops at the first matching item. If no matching
item is found, it raises a ValueError exception.
try:
i = L.index(value)
except ValueError:
i = -1 # no match
To get the index for all matching items, you can use a loop, and pass in a start
index:
L = [1,2,3,4,5]
i = -1
try:
while 1:
i = L.index(4, i+1)
print ("match at", i)
except ValueError:
pass
Example
Check if "apple" is present in the list:
OUTPUT:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
OUTPUT:
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:
OUTPUT:
OUTPUT:
Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
OUTPUT:
['apple', 'cherry']
Example
The pop() method removes the specified index, (or the last item if
index is not specified):
OUTPUT:
['apple', 'banana']
Example
The del keyword removes the specified index:
OUTPUT:
['banana', 'cherry']
Example
The del keyword can also delete the list completely:
OUTPUT:
Example
The clear() method empties the list:
OUTPUT:
[]
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().
Example
Make a copy of a list with the copy() method:
OUTPUT:
Example
Make a copy of a list with the list() method:
OUTPUT:
Example
Join two list:
OUTPUT:
Another way to join two lists are by appending all the items from list2
into list1, one by one:
Example
Append list2 into list1:
for x in list2:
list1.append(x)
print(list1)
OUTPUT:
Or you can use the extend() method, which purpose is to add elements from one
list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1.extend(list2)
print(list1)
OUTPUT:
Example
Using the list() constructor to make a List:
OUTPUT:
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first element with the specified value
cars.sort()
OUTPUT:
Syntax
list.sort(reverse=True|False, key=myFunc)
Parameter Values
Parameter Description
More Examples
Example
Sort the list descending:
cars.sort(reverse=True)
OUTPUT:
Example
Sort the list by the length of the values:
cars.sort(key=myFunc)
OUTPUT:
Example
Sort a list of dictionaries based on the "year" value of the dictionaries:
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
OUTPUT:
Example
Sort the list by the length of the values and reversed:
cars.sort(reverse=True, key=myFunc)
OUTPUT:
a = [1,2,3,4,5,6,7,8,9,10]
lower = a[0]
upper = a[9]
count = 0
for j in range(1,i+1):
if (i % j) == 0:
count = count + 1
if (count == 2):
print(i)
Output –
BINARY SEARCH
OUTPUT
Random Permutations
Random Permutations of Elements
OUTPUT
[3 4 1 5 2]
Generating Permutation of Arrays
Example
Generate a random permutation of elements of
following array:
from numpy import random
import numpy as np
print(random.permutation(arr))
OUTPUT
[5 3 4 2 1]
Python Classes/Objects
Python is an object oriented programming language.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
OUTPUT
<class '__main__.MyClass'>
Create Object
Now we can use the class named MyClass to create
objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
OUTPUT
5
The __init__() Function
The examples above are classes and objects in their simplest
form, and are not really useful in real life applications.
Example
Create a class named Person, use the __init__() function to
assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
OUTPUT
John
36
Object Methods
Objects can also contain methods. Methods in objects are
functions that belong to the object.
Example
Insert a function that prints a greeting, and execute it on the p1
object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc(
OUTPUT
It does not have to be named self , you can call it whatever you like,
but it has to be the first parameter of any function in the class:
LIST OF OBJECT IN PYTHON CLASS
We can create list of object in Python by appending
class instances to list. By this, every index in the list can point to
instance attribute and methods of class and can access them. If you
observe it closely, list of objects behaves like an array of structures
in C. Let’s try to understand it better with help of examples.
OUTPUT
Python - geometry method in Tkinter
Python has capability to create GUI applications using the Tkinter library. The library
provides many methods useful for GUI applications. The geometry method is a
fundamental one which decides the size, position and some other attributes of the
screen layout we are going to create.
Example - 1
In the below program we create a window of size 22x200 pixels using the geometry
method. Then we add a button to it and decide button position in the window using the
side and pady options.
Example
base = Tk()
base.geometry('200x200')
mainloop()
EXCEPTION HANDLING
An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.