Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page
  • 1. Subsetting Lists
  • 1.1. Single Element
  • 1.2. Multiple Elements (Slicing)
  • 2. Updating Lists
  • 2.1. Changing list elements
  • 2.2. Adding and removing elements
  • 3. List Methods
  • Conclusion

Was this helpful?

  1. Python
  2. Basics
  3. Variables and DataTypes

Lists

Python Lists are ordered collections of items, where each item can be of any data type, and they are enclosed within square brackets []. Lists support various operations such as appending, indexing, slicing, and iterating. They can contain heterogeneous data types, allowing flexibility in storing different kinds of elements like integers, strings, floats, or even other lists (nested lists). In addition, they are mutable, meaning their elements can be changed after creation, making them versatile for dynamic data storage and manipulation. Furthermore, they support indexing and slicing to access elements or sublists; and have their own methods, which we will see below.

Dataset:

basketball_champions= [
    'Los Angeles Lakers', 17,
    'Boston Celtics', 17,
    'Golden State Warriors', 7,
    'Chicago Bulls', 6,
    'San Antonio Spurs', 5,
    'Philadelphia 76ers', 3,
    'Detroit Pistons', 3,
    'Miami Heat', 3,
    'New York Knicks', 2,
    'Houston Rockets', 2,
    'Milwaukee Bucks', 2,
    'Cleveland Cavaliers', 1,
    'Atlanta Hawks', 1,
    'Washington Wizards', 1,
    'Oklahoma City Thunder', 1,
    'Portland Trail Blazers', 1,
    'Dallas Mavericks',	1,
    'Sacramento Kings',	1,
    'Toronto Raptors', 1,
    'Denver Nuggets', 1
]

1. Subsetting Lists

1.1. Single Element

# number of elements/items in a list
num = len(basketball_champions)
print(f"Number of elements: {num}")  # 40

# last element
try: 
    print(basketball_champions[40])  # error, indexing start at 0
except IndexError:
    print("Oops! Out of Index!")

# last element (again)
print(basketball_champions[39])
#or 
print(basketball_champions[num-1])
#or (preferrable)
print(basketball_champions[-1])

# first element
print(basketball_champions[0])


# OUTPUT
"""
Number of elements: 40
Oops! Out of Index!
1
1
1
Los Angeles Lakers
"""

1.2. Multiple Elements (Slicing)

# print first two teams with their championships
print(basketball_champions[0:4])

# print last two teams with their championships
print(basketball_champions[-4:])

# print only teams
print(basketball_champions[::2])


# OUTPUT
"""
['Los Angeles Lakers', 17, 'Boston Celtics', 17]
['Toronto Raptors', 1, 'Denver Nuggets', 1]
['Los Angeles Lakers', 'Boston Celtics', 'Golden State Warriors', 'Chicago Bulls', 'San Antonio Spurs']
"""

2. Updating Lists

2.1. Changing list elements

# change championship for Lakers to 25
basketball_champions[1] = 25
print(basketball_champions[:2])

# increase championship for Denver Nuggets
basketball_champions[-1] = 2
print(basketball_champions[-2:])


# OUTPUT
"""
['Los Angeles Lakers', 25]
['Denver Nuggets', 2]
"""

2.2. Adding and removing elements

# adding Phoenix Suns with 0 championships to our list
basketball_champions += ['Phoenix Suns',0]
print(basketball_champions[-6:])


# 1.Deleting by Index
# a. using del
# deleting 'Phoenix Suns' and its championships value from the list
del basketball_champions[-2:]
print(basketball_champions[-6:])

# b. using .pop()
# deleting the last element will be deleted 
basketball_champions.pop() # if no index given, then the last element will be deleted
# or the same as basketball_champions.pop(-1)
print(basketball_champions[-6:])


# Deleting by Value
# removing a specific item (first occurence of that item!)
basketball_champions.remove('Denver Nuggets')
print(basketball_champions[-6:])

# OUTPUT
"""
['Toronto Raptors', 1, 'Denver Nuggets', 2, 'Phoenix Suns', 0]
['Sacramento Kings', 1, 'Toronto Raptors', 1, 'Denver Nuggets', 2]
[1, 'Sacramento Kings', 1, 'Toronto Raptors', 1, 'Denver Nuggets']
['Dallas Mavericks', 1, 'Sacramento Kings', 1, 'Toronto Raptors', 1]
"""

In python del is a keyword and remove(), pop() are in-built methods (see section #3 for more methods). The difference between del and pop() is that even though they both delete the values at a particular index, pop() returns the deleted value:

del basketball_champions[0]
# No OUTPUT

basketball_champions.pop(0)
# OUTPUT: 'Los Angeles Lakers'

3. List Methods

Method
Description

Adds an element at the end of the list

Removes all the elements from the list

Returns a copy of the list

Returns the number of elements with the specified value

Add the elements of a list (or any iterable), to the end of the current list

Returns the index of the first element with the specified value

Adds an element at the specified position

Removes the element at the specified position

Removes the first item with the specified value

Reverses the order of the list

Sorts the list

Click on the methods practice them on W3schools

# insert Chicago Bulls and 99 to the list
basketball_champions.insert(0,'Chicago Bulls')
basketball_champions.insert(1,99)
print(basketball_champions[:6])

# retrieve Chicago Bulls index
print(basketball_champions.index('Chicago Bulls'))

# retrieve Chicago Bulls' original index
print(basketball_champions.index('Chicago Bulls',1))

# count the frequency of a specific value
print(f'Number of "Chicago Bulls" entries: {basketball_champions.count("Chicago Bulls")}')
print(f"Number of teams with single championships: {basketball_champions.count(1)}")

# OUTPUT
"""
['Chicago Bulls', 99, 'Los Angeles Lakers', 17, 'Boston Celtics', 17]
0
8
Number of "Chicago Bulls" entries: 2
Number of teams with single championships: 9
"""

# delete Chicago Bulls with 99 championships
basketball_champions.pop(0)
basketball_champions.pop(0)

Lists are great data types to store data; however, they fall short when it comes to arithmetic:

# extract championships only to do arithmetic
champs = basketball_champions[1::2]
print(champs)

# multiply each element with itself
champs * champs

# OUTPUT
"""
[17, 17, 7, 6, 5, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[76], line 4
      1 champs = basketball_champions[1::2]
      2 print(champs)
----> 4 champs * champs

TypeError: can't multiply sequence by non-int of type 'list'
"""

To do such calculation we need the help of a for loop:

# elementwise multiplication
ch_ch = [i*i for i in champs]
print(ch_ch)

# OUTPUT
"""
[289, 289, 49, 36, 25, 9, 9, 9, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1]
"""
import numpy as np

arr_champs = np.array(champs)
print(arr_champs * arr_champs)

# OUTPUT
"""
[289 289  49  36  25   9   9   9   4   4   4   1   1   1   1   1   1   1   1   1]
"""

Conclusion

Python lists are versatile data structures that can hold a collection of elements of different types. They are mutable, meaning we can modify their contents after creation. Lists support indexing and slicing to access elements or sublists and have built-in methods to operate on them more easily. They are dynamic in size and can grow or shrink as needed, making them a fundamental building block for many Python programs.

Last updated 1 year ago

Was this helpful?

A better approach would be to use the package! We first convert our list to a numpy array and then can do the multiplication without having use of a for loop.

All being said, because of the nature of the dataset we used (i.e. having only pairs of 'team' and 'championships') it is better if we use another Python's data structure called .

Numpy
Dictionary
append()
clear()
copy()
count()
extend()
index()
insert()
pop()
remove()
reverse()
sort()
Page cover image