Data Structure used in Python: List - MyPythonGuru

Jobs Search Portal and Learning point for Python,Data Science,AI,ML, Cloud and latest technologies.

Follow us on Facebook

Post Top Ad

Your Ad Spot

Thursday, July 11, 2019

Data Structure used in Python: List

Lists:

Indexing:


We are going to take a look at lists in Python. A list is a sequenced collection of different objects such as integers, strings, and other lists as well. The address of each element within a list is called an index. An index is used to access and refer to items within a list.

To create a list, type the list within square brackets [ ], with your content inside the parenthesis and separated by commas. Let’s try it!
In [1]:
# Create a list

L = ["Narendra Modi", 10.5, 2019]
L
Out[1]:
['Narendra Modi', 10.5, 2019]
We can use negative and regular indexing with a list :

In [2]:
# Print the elements on each index

print('the same element using negative and positive indexing:\n Postive:',L[0],
'\n Negative:' , L[-3]  )
print('the same element using negative and positive indexing:\n Postive:',L[1],
'\n Negative:' , L[-2]  )
print('the same element using negative and positive indexing:\n Postive:',L[2],
'\n Negative:' , L[-1]  )
the same element using negative and positive indexing:
 Postive: Narendra Modi
 Negative: Narendra Modi
the same element using negative and positive indexing:
 Postive: 10.5
 Negative: 10.5
the same element using negative and positive indexing:
 Postive: 2019
 Negative: 2019
List Content:

Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and other data structures. The same indexing conventions apply for nesting:
In [5]:
# Content List

["Narendra Modi", 10.5, 2019, [1, 2], ("A", 1)]
Out[5]:
['Narendra Modi', 10.5, 2019, [1, 2], ('A', 1)]
List Operations:

We can also perform slicing in lists. For example, if we want the last two elements, we use the following command:
In [7]:
# Operation List

L = ["Narendra Modi", 10.5,2019,"NM",1]
L
Out[7]:
['Narendra Modi', 10.5, 2019, 'NM', 1]

In [8]:
# List slicing

L[3:5]
Out[8]:
['NM', 1]

We can use the method extend to add new elements to the list:
In [10]:
# Use extend to add elements to list

L = [ "aws","azure",25]
L.extend(['ibm', 10])
L
Out[10]:
['aws', 'azure', 25, 'ibm', 10]
Another similar method is append. If we apply append instead of extend, we add one element to the list:
In [13]:
# Use append to add elements to list

L = [ "aws","azure","ibm", 10.2]
L.append(["oracle", 10])
L
Out[13]:
['aws', 'azure', 'ibm', 10.2, ['oracle', 10]]
Each time we apply a method, the list changes. If we apply extend we add two new elements to the list. The list L is then modified by adding two new elements:
In [16]:
# Use extend to add elements to list

L = [ "cloud computing","aws", 2019]
L.extend(['azure', 2020])
L
Out[16]:
['cloud computing', 'aws', 2019, 'azure', 2020]
If we append the list ['a','b'] we have one new element consisting of a nested list:
In [18]:
# Use append to add elements to list

L.append(['ibm','oracle'])
L
Out[18]:
['cloud computing', 'aws', 2019, 'azure', 2020, ['a', 'b'], ['ibm', 'oracle']]
As lists are mutable, we can change them. For example, we can change the first element as follows:
In [20]:
# Change the element based on the index

A = ["aws", 2018, 2019]
print('Before change:', A)
A[0] = 'azure'
print('After change:', A)
Before change: ['aws', 2018, 2019]
After change: ['azure', 2018, 2019]
We can also delete an element of a list using the del command:
In [21]:
# Delete the element based on the index

print('Before change:', A)
del(A[0])
print('After change:', A)
Before change: ['azure', 2018, 2019]
After change: [2018, 2019]
We can convert a string to a list using split. For example, the method split translates every group of characters separated by a space into an element in a list:
In [23]:
# Split the string, default is by space

'microsoft azure 2019'.split()
Out[23]:
['microsoft', 'azure', '2019']
We can use the split function to separate strings on a specific character. We pass the character we would like to split on into the argument, which in this case is a comma. The result is a list, and each element corresponds to a set of characters that have been separated by a comma:
In [25]:
# Split the string by comma

'cloud computing,aws,azure,ibm'.split(',')
Out[25]:
['cloud computing', 'aws', 'azure', 'ibm']

Copy and Clone List:


When we set one variable B equal to A; both A and B are referencing the same list in memory:
In [26]:
# Copy (copy by reference) the list A

A = ["aws", "iot", "ai", "azure",2019,2020]
B = A
print('A:', A)
print('B:', B)
A: ['aws', 'iot', 'ai', 'azure', 2019, 2020]
B: ['aws', 'iot', 'ai', 'azure', 2019, 2020]

Initially, the value of the first element in B is set as hard rock. If we change the first element in A to banana, we get an unexpected side effect. As A and B are referencing the same list, if we change list A, then list B also changes. If we check the first element of B we get banana instead of hard rock:
In [27]:
# Examine the copy by reference

print('B[0]:', B[0])
A[0] = "banana"
print('B[0]:', B[0])
B[0]: aws
B[0]: banana
This is demonstrated in the following figure:

You can clone list A by using the following syntax:
In [28]:
# Clone (clone by value) the list A

B = A[:]
B
Out[28]:
['banana', 'iot', 'ai', 'azure', 2019, 2020]
Variable B references a new copy or clone of the original list; this is demonstrated in the following figure:

Now if you change AB will not change:
In [29]:
print('B[0]:', B[0])
A[0] = "hard rock"
print('B[0]:', B[0])
B[0]: banana
B[0]: banana
Quiz on List

Q1. Create a list test_list, with the following elements 35, scientist[60,70,80] and cloud.
In [ ]:
# Write your code and share the result in comment section.

Q2. Find the value stored at index 1 of a_list.
In [ ]:

# Write your code and share the result in comment section.

Q3. Retrieve the elements stored at index 1, 2 and 3 of test_list.
In [ ]:

# Write your code and share the result in comment section.

Q4. Concatenate the following lists A = [1, 'a'] and B = [2, 1, 'd']:
In [ ]:

# Write your code and share the result in comment section.

Read More: Python Doc


 

2 comments:

Anonymous said...

easy to understand..

Anonymous said...

I was searching List topic since long time...now a get it..thanks MPG..

Post Top Ad

Your Ad Spot