avatarRenu Khandelwal

Summary

The provided web content is a comprehensive guide on Python lists, detailing their creation, manipulation, and various operations such as appending, inserting, removing, sorting, and copying elements.

Abstract

The webpage titled "Python Data Structures - List" offers an in-depth exploration of the list data structure in Python. It covers the fundamental aspects of lists, including their definition as a flexible, mutable collection of items, and the various methods to manipulate them. The guide begins with the basics of creating a list and progresses to more complex operations such as accessing, updating, and removing elements. It also discusses how to query lists for specific elements, find their indices, and perform in-place sorting and reversal. The article emphasizes the dynamic nature of lists, where items can be of different data types and the list can grow or shrink as needed. Additionally, it highlights the importance of understanding the difference between shallow copying and deep copying when duplicating lists to maintain data integrity. The guide is aimed at individuals with a basic understanding of programming and serves as a foundational resource for those looking to master data manipulation in Python.

Opinions

  • The author suggests that lists are a versatile and essential data structure for organizing and managing data in Python.
  • The use of code examples and outputs in bold and italics is considered an effective way to illustrate list operations.
  • The author implies that understanding list operations is crucial for efficient data handling by providing practical examples and use cases.
  • The article conveys that while lists are similar to arrays, they offer more flexibility due to their ability to hold items of different types and their dynamic resizing.
  • The author emphasizes the importance of the copy() method to create independent lists, avoiding unintended side effects when modifying one of the copies.
  • The guide recommends using list comprehensions for more efficient and readable code when performing operations like creating a list of squares or cubes.
  • The author opines that the extend() method is a convenient way to concatenate lists, mentioning that it only modifies the original list.
  • The article concludes with a quick reference section, which the author likely believes is a valuable resource for readers to use as a cheat sheet for list operations in Python.

Python Data Structures -List

All about Python List

Prerequisites: Basic knowledge of any programming language

we will explore Data Structure List and all its operations here.

I will be posting other data structures soon…

Jupyter notebook for List

What is a Data Structure?

The data structure is a way to organize data in some structures that efficient for managing, storing and retrieval.

what are the different data structures to organize data in Python?

Common data structures popularly used in Python are

List

Tuple

Sequences

Dictionary

Data Frames

List

List is like an array where data can be written as a list of comma-separated values between square brackets.

Important thing about a list is that items in a list need not be of the same type and it can be changed

Now we will go step by step into creating a list, accessing elements in a list, updating elements in a list, removing elements in a list

all outputs are in bold and italics

Creating a List called names and then displaying all its elements

names =['Tim','Harry','Sally', 'Nick','Tom','Dave','John', 'Harry']
names
['Tim', 'Harry', 'Sally', 'Nick', 'Tom', 'Dave', 'John', 'Harry']

Accessing element “0” in a list.

names[0] # displays 0th elements
'Tim'

You can also perform queries to find how many times Harry appeared in names list

names.count('Harry') 
2

you can also query if a particular value exists in a list

'maggi' in names # search maggi in names
False

If you want to find the index of the given element then you can use Index(). The index will return the lowest index of the element searched. If there are multiple instances of the element searched then the very first index will be returned.

In our example, we have two instances of the element Harry — one at index 1 and another one at index 8. Let’s query and see what we get

names.index("Harry") # find the index of value Harry
1

If the element searched is not found in the list we get “ValueError”

Inserting an element in the list at 2nd position. In Python index start from 0 so Troy will be added as the third element in the list

names.insert(2,'Troy') 
names
['Tim', 'Harry', 'Troy', 'Sally', 'Nick', Tom','Dave', 'John', 'Harry']

Appending an element at the end of the list. Insert is computationally expensive when compared to append.

names.append('Maggi') 
['Tim', 'Harry', 'Troy', 'Sally', 'Nick', 'Tom','Dave', 'John', 'Harry', 'Maggi']

Removing an element from a list using remove

names.remove('Tom') 
['Tim', 'Harry', 'Troy', 'Sally', 'Nick', 'Dave', 'John', 'Harry', 'Maggi']

we can also remove using del

del names[4]
names
['Tim', 'Harry', 'Troy', 'Sally', 'Dave', 'John', 'Harry', 'Maggi']

pop() method is used to remove an element at the specified index and it returns the value of that element.

If no index is specified then the last element in the list is removed and returned

If the index specified does not exist then we get “IndexError”

fruits =['apple','mango', 'kiwi', 'banana']
fruits.pop() # since no index specified, removes last element
'banana'
fruits.pop(1) # removes first element
'mango'
fruits.pop(5)

IndexError                                Traceback (most recent call last)
<ipython-input-69-c442968ce7a6> in <module>()
----> 1 fruits.pop(5)

IndexError: pop index out of range

we can reverse the order of the list

names.reverse() 
names
['Maggi', 'Harry', 'John', 'Dave', 'Sally', 'Troy', 'Harry', 'Tim']

we can sort the list in place. sorting in place means that the elements get reordered

names[0]
'Maggi'
names.sort() # Sorts the List inplace
names
['Dave', 'Harry', 'Harry', 'John', 'Maggi', 'Sally', 'Tim', 'Troy']
names[0]
'Dave'

Use clear() to remove all items from the list

names.clear()
names
[]

let’s understand how we can copy the contents of one list to another. In python, we can use “=” to assign one list of values to another list

cities=['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna']
cities
['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna']
world_cities = cities # copying contents of cities into world_cities
world_cities
['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna']
world_cities.append("Chicago") # appending chicago to only world_cities
['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna', 'Chicago']
cities # chicago got added to cities too as we had used assignment operator
['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna', 'Chicago']
cities.append("London")
cities
['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna', 'Chicago', 'London']
world_cities
['Paris', 'New York', 'Prague', 'San Francisco', 'Vienna', 'Chicago', 'London']

when we use assignment operator we see that when we make a change in one list, it gets reflected in the other list too.

How can we copy the contents of one list into another list but ensure that when one list changes it does not modify the other list

we can use copy(), it will create a shallow copy of the list. Shallow copy is when you change the content of one list and the other list remain unmodified.

trees =['Oak', 'Birch', 'Maple']
trees
['Oak', 'Birch', 'Maple']
forest_trees = trees.copy()  
forest_trees
['Oak', 'Birch', 'Maple']
forest_trees.insert(2, 'Cypress') # inserting cypress 
forest_trees
['Oak', 'Birch', 'Cypress', 'Maple']
trees
['Oak', 'Birch', 'Maple']

In the above example, we created a forest_trees as a shallow list of trees by using copy(). we then added “Cypress” to forest_tress. trees were still not modified.

Next, let’s find unique elements in a list.

First adding a duplicate element in trees

trees.append('Birch')
trees
['Oak', 'Birch', 'Maple', 'Birch']

Now we find unique elements in trees

unique_trees = []
[unique_trees.append(i) for i in trees if i not in unique_trees]
unique_trees
['Oak', 'Birch', 'Maple']

Now we know basic operations on a List, let’s try to first iterate thru all the elements in a list.

extend() method extends the list by appending the elements at the end of the specified list in the argument.

extend() only modifies the original list

cars = ['Toyota Prius', 'Honda CRV', 'Honda Accord']
electric_cars =['Tesla']
cars.extend(electric_cars) 
cars
['Toyota Prius', 'Honda CRV', 'Honda Accord', 'Tesla']
electric_cars
['Tesla']

Here I am creating a list and then using a for loop to iterate through its elem

squares=[] # create an empty list
for i in range(10): # does not take the last index so the loop will iterate from 0 to 9
    squares.append(i**2)
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This can be made more efficient by using list comprehensions.

cubes =[]
cubes = [i**3 for i in range(10)]
cubes
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

List Operations quick reference

append() : adds an element at the end of the list

insert() : adds element at the specified position

count() : returns the number of times specified element appeared in the list

index() : returns the lowest index of the element searched

remove() : removes specified element from the list

del() : deletes the element at the specified index

pop() : removes and returns the element at the specified index. If the index is not specified then it returns the last element

sort() : sort the list elements

reverse() : reverses the order of the list

clear() : clears or removes all elements from a list

copy() : returns a shallow copy of the list

extend() : extends the list by appending all the items from the list specified in the argument

Python
Data Structure
List
List Operations
Data Science
Recommended from ReadMedium