Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Lists in Python

Lists in python (basics)

Uploaded by

carlgta2915
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lists in Python

Lists in python (basics)

Uploaded by

carlgta2915
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Lists in Python

Lists in Python with Examples


In this article, I am going to discuss Lists in Python with
examples. x
o Python Data structures
o Sequence of elements
o What is List in Python
o Creating list
o Difference between list() function and list class
o Mutability
o Accessing elements in the list
o Important functions and methods in the list
o Difference between append and insert
o Difference between remove() and pop() methods
o Ordering elements of List:
o Aliasing and Cloning of list objects
o Mathematical + and * operators
o Comparison of lists
o Membership operators
o Nested Lists
o List comprehensions

Python Data Structures:


In python, there are quite a few data structures available. They
are used to store a group of individual objects as a single entity.
Sequences
Sequences are those, which contain a group of elements, whose
purpose is to store and process a group of elements. In python,
strings, lists, tuples, and dictionaries are very important
sequence data types.
Lists in Python:
A list is a data structure that can store a group of elements or
objects. It has the following features/properties:
1. Lists can store the same
2. type as well as different types of elements. Hence, it is
heterogeneous.
3. Lists have dynamic nature which means we don’t need to
mention the size of the list while declaring as we do for
arrays in other programming languages. The size will
increase dynamically.
4. Insertion order is preserved. The order, in which the items
are added to a list, is the order in which output is displayed.
5. The list can store duplicates elements.
6. In lists, the index plays the main role. Using index we
perform almost all the operations on the items in it.
7. List objects are mutable which means we can modify or
change the content of the list even after the creation.
Creating a list in Python
There are a couple of ways to create a list in Python. Let’s see
them with examples.
Creating a list in Python by using square brackets ‘[]’
We can create a list in python by using square brackets ‘[]’. The
elements in the list should be comma-separated.
Example: Creating an empty list (demo1.py)
l1 = []
print(l1)
print(type(l1))
Output:

Example: Creating a list with elements (demo2.py)


names = ["Mohan", "Prasad", "Ramesh", "Mohan", 10, 20, True,
None]
print(names)
Output:
You can observe from the output that the order is preserved and
also duplicate items are allowed. It can contain mixed data types
(strings, integers, boolean, None) elements.
Creating a list in Python by using the list() function
You can create a list by using the list() function in python.
Generally, we use this function for creating lists from other data
types like range, tuple, etc. This is generally referred to as type
conversion
Example: Creating a list using list() function (demo3.py)
r=range(0, 10)
l=list(r)
print(l)
Output:
Difference between list() function and list class in python:
list() is a predefined function in python. list() function is used to
convert other sequences or data types into list data types.
The list is a predefined class in python. Once we create a list then
it is internally represented as a list class object type. We can
check this by using a type function.
Example: Creating a list using list() function (demo3.py)
r=range(0, 10)
l=list(r)
print(l)
print(type(l))
Output:

Example: Mutability (demo4.py)


l = [1, 2, 3, 4, 5]
print(l)
print("Before modifying l[0] : ",l[0])
l[0]=20
print("After modifying l[0] : ",l[0])
print(l)
Output:

Accessing List in Python:


There are three ways in which you can access the elements in the
list in python. They are:
a. By using indexing
b. By using the slicing operator
c. By using loops

Accessing List By using indexing in Python:


This way is the same as we have seen for the string data type.
Accessing the elements by index means, accessing by their
position numbers in the list. Index starts from 0 onwards. List
also, just as strings, supports both positive and negative
indexes. The positive index represents from left to right direction
and the negative index represents from right to left direction.
Note: IndexError: If we are trying to access beyond the range of
list index, then we will get IndexError.
Example: List Indexing (demo5.py)
names = ["Prabhas", "Prashanth", "Prakash"]
print(names)
print(names[0])
print(names[1])
print(names[2])
print(type(names))
print(type(names[0]))
print(type(names[1]))
print(type(names[2]))
Output:

Example: List index out of range error (Demo6.py)


names = ["Prabhas", "Prashanth", "Prakash"]
print(names)
print(names[0])
print(names[1])
print(names[2])
print(names[10])
Output:

Accessing List By using slicing operator in Python


Slicing is the way of extracting a sublist from the main list. The
syntax is given below.
list_name[start: stop: stepsize]
start represents the index from where we slice should start, the
default value is 0. stop represents the end index where the slice
should end. The max value allowed is the length of the list. If no
value is provided, then it takes the last index of the list as the
default value. stepsize represents the increment in the index
position of the two consecutive elements to be sliced. The result
of the slicing operation on the list is also a list i.e it returns a list.
Example: Slicing (Demo7.py)
n = [1, 2, 3, 4,5, 6]
print(n)
print(n[2:5:2])
print(n[4::2])
print(n[3:5])
Output:
Accessing List By using loops in Python:
We can also access the elements of a list using for and while
loops
Example: Accessing list using loops (demo8.py)
a = [100, 200, 300, 400]
for x in a:
print(x)
Output:
l1 = [3,5,6,7,8,1,2,88]

x = int(input("Enter the Item :"))


loc = 0
for i in l1:
if(i == x):
print("item is found at ",loc)
break
else:
loc+=1
else:
print('item not found ')

%runfile C:/Users/ashis/untitled4.py --wdir


Enter the Item :6
item is found

%runfile C:/Users/ashis/untitled4.py --wdir


Enter the Item :2
item is found at 2

%runfile C:/Users/ashis/untitled4.py --wdir


Enter the Item :2
item is found at 6
Another Approach
Example: Accessing list using loops (demo9.py)
l1 = [3,5,6,7,8,1,2,88]
x = int(input("Enter the Item :"))
for i in range(len(l1)):
if (x == l1[i]):
print("item is found at ",i)
break
else:
print('item not found ')

a = [100, 200, 300, 400]


x=0
while x<len(a):
print(a[x])
x = x+1
Output:

IMPORTANT FUNCTIONS OR METHODS OF LISTS IN PYTHON


In python, a method and functions are one and the same. There
is not much difference between them. It will be clearly explained
in the OOPS concepts. For now, just remember function and
method are the same.
len() method in python:
This function when applied to a list will return the length of the
elements in it.
Example: len() function (demo10.py)
n = [1, 2, 3, 4, 5]
print(len(n))
Output: 5
count() function in Python:
This method returns the number of occurrences of a specific
item in the list
Example: count() method (demo11.py)
n = [1, 2, 3, 4, 5, 5, 5, 3]
print(n.count(5))
print(n.count(3))
print(n.count(2))
Output:
append() method in Python:
Using this method we can add elements to the list. The items or
elements will be added at the end of the list.
Example: append() method (demo12.py)
l=[]
l.append("Ramesh")
l.append("Suresh")
l.append("Naresh")
print(l)
Output:

insert() method in Python:


We can add elements to the list object by using the insert()
method. The insert() method takes two arguments as input: one
is the index and the other is the element. It will add the elements
to the list at the specified index.
Parameter:
• index - The first argument is the index of the element
before which to insert.
• element - Element to be inserted in the list.
Return Value from insert() method
None. It only updates the current list.

Example: insert() method (demo13.py)


n=[10, 20, 30, 40, 50]
n.insert(0, 76)
print(n)
Output:
Difference between append and insert in Python
Both methods are used to add elements to the list. But the
difference between them is that the append will add the
elements to the last, whereas the insert will add the elements at
the specified index mentioned.
While you are using the insert() method,
a. If the specified index is greater than the max index, then the
element will be inserted at the last position.
b. If the specified index is smaller than the min index, then the
element will be inserted at the first position.
Example: insert() method (demo14.py)
l=[10, 20, 30, 40]
print(l) # [10, 20, 30, 40]
l.insert(1, 111)
print(l) # [10, 111, 20, 30, 40]
l.insert(-1, 222)
print(l) # [10, 111, 20, 30, 222, 40]
l.insert(10, 333)
print(l) # [10, 111, 20, 30, 222, 40, 333]
l.insert(-10, 444)
print(l) # [444, 10, 111, 20, 30, 222, 40, 333]
Output:x

extend() method in Python:


Using this method the items in one list can be added to the
other.
Example: extend() method (demo15.py)
l1 = [1,2,3]
l2 = ['Rahul', 'Rakesh', 'Regina']
print('Before extend l1 is:', l1)
print('Before extend l2 is:', l2)
l2.extend(l1)
print('After extend l1 is:', l1)
print('After extend l2 is:', l2)
Output:

Example: extend() method (demo16.py)


august_txns = [100, 200, 500, 600, 400, 500, 900]
sept_txns = [111, 222, 333, 600, 790, 100, 200]
print("August month transactions are : ",august_txns)
print("September month transactions are : ",sept_txns)
sept_txns.extend(august_txns)
print("August and Sept total transactions amount:
",sum(sept_txns))
Output:

remove() method in Python:


We can use this method to remove specific items from the list.
Example: remove() method (demo17.py)
n=[1, 2, 3]
n.remove(1)
print(n)
Output:
If the item exists multiple times, then only the first occurrence
will be removed. If the specified item not present in list, then we
will get ValueError. Before removing elements it’s a good
approach to check if the element exists or not to avoid errors.
Example: remove() method (demo18.py)
n=[1, 2, 3, 1]
n.remove(1)
print(n)
Output:
Example: remove() method (demo19.py)
n=[1, 2, 3, 1]
n.remove(10)
print(n)
Output:
pop() method in Python:
This method takes an index as an argument and removes and
returns the element present at the given index. If no index is
given, then the last item is removed and returned by default. If
the provided index is not in the range, then IndexError is thrown.
Example: pop() method (demo20.py)
n=[1, 2, 3, 4, 5]
print(n.pop(1))
print(n)

print(n.pop())
print(n)
Output:
Example: pop() method (demo21.py)
n=[1, 2, 3, 4, 5]
print(n.pop(10))
Output:
Difference between remove() and pop()
del V/S remove() the V/Spop()

del remove() pop()

del is a keyword. It is a method. pop() is a method.

To delete value this This method also


To delete value it method uses the uses the index as a
uses the index. value as a parameter to
parameter. delete.

The del keyword The remove()


pop() returns
doesn’t return method doesn’t
deleted value.
any value. return any value.

The del keyword


can delete the
At a time it deletes At a time it deletes
single value from
only one value only one value from
a list or delete the
from the list. the list.
whole list at a
time.

It throws index It throws value It throws index


error in case of error in case of error in case of an
the index doesn’t value doesn’t exist index doesn’t exist
exist in the list. in the list. in the list.
Ordering the elements in list:
reverse() method in python:
This method reverses the order of list elements.
Example: reverse() method (demo22.py)
n=[1, 2, 3, 4, 'two']
print(n)
n.reverse()
print(n)
Output:

sort() method in Python:


In a list by default insertion order is preserved. If we want to sort
the elements of the list according to the default natural sorting
order then we should go for the sort() method. For numbers, the
default natural sorting order is ascending order. For strings, the
default natural sorting order is alphabetical order. To use the
sort() method, the list should contain only homogeneous
elements, otherwise, we will get TypeError.
Example: sort() method (demo23.py)
n=[1, 4, 5, 2, 3]
n.sort()
print(n)
s=['Suresh', 'Ramesh', 'Arjun']
s.sort()
print(s)
Output:

Example: sort() method (demo24.py)


n=[1, 4, 5, 2, 3, 'Suresh', 'Ramesh', 'Arjun']
n.sort()
print(n)
Output:
LIST ALIASING and CLONING in PYTHON:
Aliasing List in Python:
The process of giving a new name to an existing one is called
aliasing. The new name is called an alias name. Both names will
refer to the same memory location. If we do any modifications to
the data, then it will be updated at the memory location. Since
both the actual and alias name refer to the same location, any
modifications done on an existing object will be reflected in the
new one also.
Example: aliasing (demo25.py)
x=[10, 20, 30]
y=x
print(x)
print(y)
print(id(x))
print(id(y))

x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))
Output:

Cloning in List:
The process of creating duplicate independent objects is called
cloning. We can implement cloning by using the slice operator or
by using the copy() method. These processes create a duplicate
of the existing one at a different memory location. Therefore,
both objects will be independent, and applying any modifications
to one will not impact the other.
Example: Cloning using slicing operator (demo26.py)
x=[10, 20, 30]
y=x[:]
print(x)
print(y)
print(id(x))
print(id(y))

x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))
Output:

Example: Cloning by using copy() method (demo27.py)


x=[10, 20, 30]
y=x.copy()
print(x)
print(y)

print(id(x))
print(id(y))
Output:

MATHEMATICAL OPERATORS on LIST


The concatenation operator (+): “+” operator concatenates two
list objects to join them and returns a single list. For this, both
the operands should be list type, else we will get TypeError
Example: Concatenation (demo28.py)
a= [1, 2, 3]
b= [4, 5, 6]
c=a+b
print(c)
Output:
[1, 2, 3, 4, 5, 6]

Example: TypeError (demo29.py)


a= [1, 2, 3]
b= 'Balu'
c=a+b
print(c)
Output:
TypeError: can only concatenate list (not "str") to list
Multiplication operator in Lists:
The “*” operator works to repeat elements in the list by the said
number of times. For this one operand should be list and the
other operand should be an integer, else we get TypeError
Example: Multiplication operator (demo30.py)
a = [1, 2, 3]
print(a)
print(2*a)
Output:
[1, 2, 3]
[1, 2, 3, 1, 2, 3]

COMPARISON of LISTS in Python


We can use relational operators (<, <=,>,>=) on the List objects
for comparing two lists. Initially, the first two items are
compared, and if they are not the same then the corresponding
result is returned. If they are equal, the next two items are
compared, and so on
Example: Comparison Operators (demo31.py)
print([1, 2, 3] < [2, 2, 3])
print([1, 2, 3] < [1, 2, 3])
print([1, 2, 3] <= [1, 2, 3])
print([1, 2, 3] < [1, 2, 4])
print([1, 2, 3] < [0, 2, 3])
print([1, 2, 3] == [1, 2, 3])
Output:
True
False
True
True
False
True

While comparing lists that are loaded with strings the following
things are considered for the comparison.

a. The number of elements


b. The order of elements
c. The content of elements (case sensitive)
Example: Comparison of lists (demo32.py)
x =["abc", "def", "ghi"]
y =["abc", "def", "ghi"]
z =["ABC", "DEF", "GHI"]
a =["abc", "def", "ghi", "jkl"]

print(x==y)
print(x==z)
print(x==a)
Output:
True
False
False
MEMBERSHIP OPERATORS IN LIST
We can check if the element is a member of a list or not by using
membership operators. They are:
a. in operator
b. not in operator
If the element is a member of the list, then the in operator
returns True otherwise False. If the element is not in the list,
then not in operator returns True otherwise False.
Example: Membership operators (demo33.py)
x=[10, 20, 30, 40, 50]
print(20 in x) # True
print(20 not in x) # False
print(90 in x) # False
print(90 not in x) # True
Output:
True
False
False
True

NESTED LISTS in Python:


A list within another list is called a nested list. It is possible to
take a list as an element in another list.
Let’s understand it with example.
Example: Nested Lists (demo34.py)
a = [80, 90]
b = [10, 20, 30, a]
print(b[0])
print(b[1])
print(b[2])
print(b[3])
Output:
LIST COMPREHENSIONS IN PYTHON:
List comprehensions are the precise way of creating a list using
iterable objects like tuples, strings, lists etc. Generally, for
multiplying each element of a list with 2, we take a for loop and
taking one item at a time, multiply it with 2 and finally save the
value in a new list.
Example: Multiplying with 2 (demo35.py)
Without list comprehension
x = [1, 2, 3, 4]
y = []

for i in x:
y.append(i*2)

print(x)
print(y)

Output:
[1, 2, 3, 4]
[2, 4, 6, 8]
The above code can be written in a single line using list
comprehensions.
Example: List Comprehensions (demo36.py)
x = [1, 2, 3, 4]
y = [ i*2 for i in x]
print(y)
Output:
[2, 4, 6, 8]

Syntax for list comprehension would be

list = [expression for item1 in iterable1 if statement]

Here Iterable represents a list, set, tuple, dictionary, or range


object. The result of list comprehension is a new list based on the
applying conditions.
l1 = [2,5,8,11,50]

l2=[]
for i in l1:
if (i%2 == 0):
l2.append(i*2)
print(l2)
[4, 16, 100]

Example: List Comprehensions (demo37.py)


s=range(1, 20, 3)

for i in s: #This loop is for knowing what is in s


print(i)
m=[x for x in s if x%2==0] #List comprehension
print(m)
Output:

Python List Comprehension


List comprehension offers a concise way to create a new list
based on the values of an existing list.
Suppose we have a list of numbers and we desire to create a new
list containing the double value of each element in the list.
numbers = [1, 2, 3, 4]
# list comprehension to create new list
doubled_numbers = [num * 2 for num in numbers]
print(doubled_numbers)
Run Code
Output
[2, 4, 6, 8]
Here is how the list comprehension works:

Python List Comprehension

Syntax of List Comprehension


[expression for item in list if condition == True]
Here, for every item in list, execute
the expression if the condition is True.
Note: The if statement in list comprehension is optional.
for Loop vs. List Comprehension
List comprehension makes the code cleaner and more concise
than for loop.
Let's write a program to print the square of each list element
using both for loop and list comprehension.
for Loop
numbers = [1, 2, 3, 4, 5]
square_numbers = []
# for loop to square each elements
for num in numbers:
square_numbers.append(num * num)
print(square_numbers)
# Output: [1, 4, 9, 16, 25]

List Comprehension
numbers = [1, 2, 3, 4, 5]
# create a new list using list comprehension
square_numbers = [num * num for num in numbers]
print(square_numbers)
# Output: [1, 4, 9, 16, 25]

Conditionals in List Comprehension


List comprehensions can utilize conditional statements
like if…else to filter existing lists.
Let's see an example of an if statement with list comprehension.

# filtering even numbers from a list


even_numbers = [num for num in range(1, 10) if num % 2 == 0 ]
print(even_numbers)
# Output: [2, 4, 6, 8]

Here, list comprehension checks if the number from range(1,


10) is even or odd. If even, it appends the number in the list.
Note: The range() function generates a sequence of numbers. To
learn more, visit Python range().
if...else With List Comprehension

Nested if With List Comprehension


if...else With List Comprehension
Let's use if...else with list comprehension to find even and odd
numbers.
l1 = [2,5,8,11,5]

l2=["Even" if x %2==0 else "Odd" for x in l1]

print(l2)

Output
['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
Here, if an item in the numbers list is divisible by 2, it
appends Even to the list even_odd_list. Else, it appends Odd.

We can also use nested loops in list comprehension. Let's write


code to compute a multiplication table.

multiplication = [[i * j for j in range(1, 6)] for i in range(2, 5)]


print(multiplication)

Nested if With List Comprehension


Let's use nested if with list comprehension to find even numbers
that are divisible by 5.

# find even numbers that are divisible by 5


num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
Run Code
Output
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Here, list comprehension checks two conditions:
c. if y is divisible by 2 or not.
d. if yes, is y divisible by 5 or not.
If y satisfies both conditions, the number appends to num_list.

Example: List Comprehension with String


We can also use list comprehension with iterables other than
lists.
word = "Python"
vowels = "aeiou"
# find vowel in the string "Python"
result = [char for char in word if char in vowels]
print(result)
# Output: ['o']
Run Code
Here, we used list comprehension to find vowels in the
string 'Python'.

More on Python List Comprehension


Nested List Comprehension
We can also use nested loops in list comprehension. Let's write
code to compute a multiplication table.
l1 = list(range(2,6))
print(l1)
l2 = [
[i * j for j in range(1, 11)]
for i in l1]
print(l2)
Run Code
Output
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
Here is how the nested list comprehension works:

Nested Loop in List Comprehension


Let's see the equivalent code using nested for loop.
Equivalent Nested for Loop
multiplication = []
for i in range(2, 5):
row = []
for j in range(1, 6):
row.append(i * j)
multiplication.append(row)
print(multiplication)
Run Code
Here, the nested for loop generates the same output as the
nested list comprehension. We can see that the code with list
comprehension is much cleaner and concise.
Ternary Operator in Python
The ternary operator in Python is a concise way to write simple
if-else statements. It has the following syntax:
condition_if_true if condition else condition_if_false
Here, condition is a boolean expression that evaluates to
either True or False.

If condition is True, the expression returns condition_if_true.


If condition is False, the expression returns condition_if_false.

Example 1: Simple Ternary


x=5
result = "Greater" if x > 3 else "Less"
print(result) # Output: Greater

You might also like