02 Python Lists

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Python Lists

• Compound data type


• Separated by commas and enclosed within [ ]
• Similar to Arrays but all items belonging to a list can be of different data types.
• Index starts at 0.
• + sign is a concatenation operator
• * is repetition operator
• Elements/Items can be changed.
• List size can be modified.

Creating List

MyList = []
print("Blank List: ")
print(MyList)

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing using index


List = ["All", "is", "Well"]
print("\nList Items: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['All', 'is'], ['Well']]
print("\nMulti-Dimensional List: ")
print(List)

Length (size) of a List

print(len(List1))

Accessing Elements from a List

List = ["All", "is", "Well"]


# accessing a element from the list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [[‘All’, 'is'], ['Well']]

# accessing an element from the Multi-Dimensional List using index number


print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Negative indexing

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Slicing of a List
In Python List, there are multiple ways to print the whole List with all the elements, but to print a
specific range of elements from the list, we use the Slice operation. Slice operation is performed
on Lists with the use of a colon(:).
• To print elements from beginning to a range use [: Index]
• to print elements from end-use [:-Index]
• to print elements from specific Index till the end use [Index:]
• to print elements within a range, use [Start Index:End Index]
• to print the whole List with the use of slicing operation, use [:]
• to print the whole List in reverse order, use [::-1]
List Methods
Function Description

Append() Add an element to the end of the list

Extend() Add all elements of a list to another list

Insert() Insert an item at the defined index

Remove() Removes an item from the list

Pop() Removes and returns an element at the given index

Clear() Removes all items from the list

Index() Returns the index of the first matched item

Count() Returns the count of the number of items passed as an argument

Sort() Sort items in a list in ascending order

Reverse() Reverse the order of items in the list

copy() Returns a copy of the list


String join() Method
Python String join() method is a string method and returns a string in which the elements of the
sequence have been joined by the str separator.

list1 = ['1','2','3','4']
s = "-"
s = s.join(list1)
print(s)

output: 1-2-3-4

String split() Method


Split a string into a list where each word is a list item:
txt = "welcome to Python Programming"
x = txt.split()
print(x)

output: ['welcome', 'to', 'Python', 'Programming']

Copy a list
Aliasing Lists
In Python, you might use the = operator copy of an object. It is tempting to think this creates a new
object, but it doesn't. Instead, it creates a new variable that refers to the original object. This means
changing a value in the copied object changes the value of the original object as well.

a = [1, 2, 3]
b=a
b[0] = 100
print(a: ', a)
print(b: ', b)
Output:
a: [100, 2, 3]
b: [100, 2, 3]

As a and b now point to the same list, updating one always updates the other.

To verify that both objects really refer to the same object, you can also use the id() method. Each
Python object has a unique ID. If you check the IDs of the a and b, you can see they are the exact same:

print(id(a))
print(id(b))

Output:
139804802851400
139804802851400

How To Copy in Python


Let’s go over a common example: You want to take a copy of a list in such a way that the original list
remains unchanged when updating the copied list. There are two ways to copy in Python:
• Shallow copy
• Deep copy
Both of these methods are implemented in the copy module. To use these, you need to import the
copy module into your project.
To take a shallow copy, call copy.copy(object).
To take a deep copy, call copy.deepcopy().

Shallow copy
A shallow copy is shallow because it only copies the object but not its child objects. Instead, the child
objects refer to the original object’s child objects.

import copy
groups = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_groups = copy.copy(groups)
Here, you have groups, which is a list of lists of numbers. And you have a shallow copy called
new_groups. Let’s examine these:

1. The ID of groups is not the same as the ID of new_groups, which is reasonable, as new_groups is a
copy of groups.

print(id(groups), id(new_groups))
Output:
140315092110600 140315092266184

It seems as if new_groups was a completely independent copy of groups. But let’s take it a step further
to see that it’s not.

2. Here is where the shallowness becomes evident. The IDs of the lists in the new_groups are equal to
the IDs of the lists of the original groups:

print(id(groups[0]), id(new_groups[0]))
Output:
140315092110664 140315092110664

The shallowness means only the “outer” list gets copied. But the inner lists still refer to the lists of the
original list. Due to this, changing a number in the copied list affects the original list:

new_groups[0][0] = 100000
print(new_groups[0])
print(groups[0])
Output:
[100000, 2, 3]
[100000, 2, 3]

3. The “outer” list of new_groups is a “real” copy of the original groups. Thus, you can add new
elements to it or even replace existing ones. These changes won’t affect the original groups list.
For example, let’s replace the first list in new_groups with a string. This should not affect groups.
new_groups[0] = "Something else"
print(new_groups)
print(groups)
Output:
Something else
[100000, 2, 3]

Deep copy
A deep copy creates a completely independent copy of the original object.

import copy
groups = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_groups = copy.deepcopy(groups)

The IDs of groups and new_groups do not match:

print(id(groups), id(new_groups))
Output:
140416138566984 140416138739016

2. The IDs of the lists in new_groups are not equal to the IDs of the lists in groups:

print(id(groups[0]), id(new_groups[0]))
Output:
140416138567048 140416138566728

Changing a number in new_groups doesn’t change that value in the original groups.

new_groups[0][0] = 100000
print(new_groups[0])
print(groups[0])
Output:
[100000, 2, 3]
[1, 2, 3]

3. The new_groups is an independent copy of groups. Thus, there is no way changes made in
new_groups would be visible in the original groups.

new_groups[0] = "Something else"


print(new_groups)
print(groups)
Output:
Something else
[1, 2, 3]

List copy() method


The copy() method returns a shallow copy of the list.
a = [2, 3, 5]
# copying a list
b = a.copy()
print('Copied List:', b)
# Output: Copied List: [2, 3, 5]

Shallow Copy vs Deep Copy

A shallow copy means if we modify any of the nested list elements, changes are reflected in both the
list as they point to the same reference.
Whereas in deep copy, when we add an element in any of the lists, only that list is modified.

When we use the “=” operator the new list refers to the same object, hence any change (append,
remove, change of value) in one list is reflected on both.

But when we use the list.copy() method, changes made to one list or not reflected on other except for
in nested elements (like list within a list), Here we should use the copy.deepcopy() from the copy
module to avoid this problem.

Techniques to deep copy:


Using copy.deepcopy()
Techniques to shallow copy:
Using copy.copy()
Using list.copy()
Using slicing

Packing and Unpacking Lists


The process of assigning values to a list is called packing. The unpacking is the process of extracting
the values from the list and assigning them to variables. If we want to unpack the entire list then the
number of variables should be the same as the number of elements in the list.

list1 = [10, 20, 30] # list packing


var1, var2, var3 = list1 # list unpacking

You might also like