Latest Web Stories

1

Exploring Smartphone Influence on the Brain: Neurological Perspectives

2

Angular vs. React: Which One Should You Choose?

3

Discover Serenity: Your Guide to Mindfulness Apps

4

Discover how smartphone apps can enhance your mindfulness practice: 5 Senses Exercise with Apps

5

Discover How Smartwatches Measure Blood Pressure: Explained Simply

6

13 Exciting Games Launching in April 2024: From Freedom Planet 2 to TopSpin 2K25!

7

Discover the 5 Amazon Big Spring Deals on Tablets from Samsung, Lenovo

8

Big Savings Alert: Amazfit Smart Watches Now on Sale on Amazon!

9

Amazon's Big Spring Sale: Top 6 Anker Souncore Headphones and Earbuds Deals

10

Affordable VR Adventures: The Best Budget VR Headsets

11

Fly in Peace: Discover the Ultimate Noise-Cancelling Headphones for Flying

12

Bringing AI to Life: NVIDIA's Digital Human Technolgies in Healthcare, Gaming, and More

13

Discover Exciting New Games on NVIDIA GeForce NOW!

14

Steam Spring Sale 2024 is here: Explore the 10 Best FPS Games

15

The Future of iPhones: Apple's Bold Step into AI with DarwinAI

16

Discover the Magic of Sonos Soundbar: Transform Your Home Entertainment Experience!

17

Enhance Your Home Fun: 5 Best Sonos Soundbars to Amp Up Your Entertainment!

18

Pinterest Introduces AI-Powered Body Type Ranges for Inclusive Searches

19

Embrace the Next Wave: 35+ AI Tools for Enhanced Productivity in 2024

20

Xbox Gaming Bonanza: Lots of New Games with Xbox Game Pass!

21

Sony Paves the Way for Gaming Evolution with 'Super-Fungible Tokens' Patent

22

Smart Printing Choices: 10 Key Factors to Consider When Buying an HP Printer or Any Printer

23

Projector Picks: Explore the Best Mini Projectors for Big Screen Fun!

24

JavaScript Essentials: Your Quick Start to Web Coding

25

Gaming Laptop Guide 2024: 10 Crucial Checks Before You Buy + Top 5 Picks for you!

26

Gaming Joy Awaits: Explore the Best PS5 Games of 2024

27

Epic Games Special: Dive into Astro Duel 2 for FREE this week. See What’s Coming Next Week!

28

Fitbit Fitness Tracker Guide 2024: Choose Your Perfect Fit

29

Feel the Beat: Exploring Top Over-Ear Headphones

30

Explore the Web Development Strategies in 2024: A Developers Handbook

31

Explore Must-Play Nintendo Switch Games in 2024!

32

Eclipse Ready: CE and ISO Certified Solar Eclipse Glasses for a Safe Sky Spectacle

33

Disney and Pixar’s Inside Out 2 Introduces New Emotions to Riley's World

34

Discover Waze's cool new features for safer and happier drives!

35

Discover the Top Picks: Best Smartwatches for Your Lifestyle

36

Discover the Best Smartphones Trending Now: Your Easy Guide to the Best Picks!

37

Sound Revolution: Discover the Best Bluetooth Speakers of 2024!

38

Discover the 10 Best Productivity Apps to Supercharge Your Daily Tasks

39

Discover,Install and Enjoy: The Best Chrome Extensions for Developers in 2024

40

Crack the Code: Your Guide to Computer Programming Magic in 2024

41

Boost Your Content Creation: 10 ChatGPT Prompts to Supercharge Content Creation Productivity

42

10 Best Tech Companies in Silicon Valley

43

Top 10 Web Development Interview Questions you can...

44

Learn how to Answer Tell me about Yourself

45

5 Books You Need to Read Right Now

46

25 Practical Ways to Earn Money Online

Translate this page in your preferred language:


Python Lists: A Comprehensive Guide with Codes and Examples in 2023

Article by: Manish Methani

Last Updated: October 5, 2021 at 2:04pm IST
6 min 56 sec read

Introduction to Python Lists

In Python, a list is a collection of ordered, mutable, and heterogeneous elements. Lists are one of the most commonly used data types in Python as they allow you to store and manipulate multiple items in a single variable.

Creating a Python List

You can create a Python list using square brackets [] and separating each element with a comma. For example:

my_list = [1, 2, 3, "hello", True]

In this example, we have created a list containing integers, a string, and a boolean value.

Accessing Elements in a Python List

You can access elements in a Python list using their index value. The index value starts from 0 for the first element and increases by 1 for each subsequent element. For example:

my_list = [1, 2, 3, "hello", True]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: hello

You can also use negative indexing to access elements from the end of the list. For example:

my_list = [1, 2, 3, "hello", True]
print(my_list[-1]) # Output: True
print(my_list[-2]) # Output: hello

Modifying a Python List

You can modify elements in a Python list by assigning new values to them. For example:

my_list = [1, 2, 3, "hello", True]
my_list[3] = "world"
print(my_list) # Output: [1, 2, 3, "world", True]

In this example, we have modified the element at index 3 from "hello" to "world".

Adding and Removing Elements from a Python List

You can add elements to a Python list using the append() method. For example:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

You can also remove elements from a Python list using the remove() method. For example:

my_list = [1, 2, 3, 4]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4]

You can also remove elements from a Python list using the del keyword. For example:

my_list = [1, 2, 3, 4]
del my_list[2]
print(my_list) # Output: [1, 2, 4]

The basic example of List

# Create a list
ls = [5, 7, 25]

# Prints the type of the variable
print(type(ls))

# Print the contents of the list
print(ls)

# elementwise indexing in the list
print(ls[0], ls[1], ls[2])

# Append an element at the end of the list
ls.append(45)
print(ls)

# Remove and return the last element of the list
x = ls.pop()
print(x, ls) 

Example 2

# Unlike arrays, list can contain elements of different datatypes
ls = ["codzify", ".com", 23]

# Print the contents of the list
print(ls)

# indexing in the list
print(ls[0], ls[1], ls[2])

# Append an element at the end of the list
ls.append("hello world")
print(ls)

# Remove and return the last element of the list
x = ls.pop()
print(x, ls) 

Slicing a Python List

You can slice a Python list to extract a subset of elements from it. Slicing is done using the colon : operator. For example:

my_list = [1, 2, 3, "hello", True]
print(my_list[1:4]) # Output: [2, 3, "hello"]

In this example, we have sliced the list to extract elements from index 1 to index 3.

Try to execute the code to see the output.

ls = list(range(6))
print(ls)

# Negative Indexing is also possible, it will print from the end of the list
print(ls[-1], ls[-2], ls[-3])

# Get a sublist starting from index 1 to 3 (the last index is exclusive)
print(ls[1:4])

# Get a sublist starting from index 2 to the end
print(ls[2:])

# Get a sublist from start to index 3 (the last index is exclusive)
print(ls[:4])

# Get the whole list
print(ls[:])

# Assign a new sublist to a slice
ls[2:4] = ["codzify", "python"]
print(ls) 

Iterating over a Python List

You can iterate over a Python list using a for loop. For example:

my_list = [1, 2, 3, 4]
for element in my_list:
    print(element)

List Comprehensions

List comprehension is a powerful feature of Python programming that allows you to create a new list by applying a transformation to each element of an existing list. It is a concise and elegant way to write code and can help to simplify complex algorithms. With list comprehension, you can avoid writing lengthy code using for loops and if statements. This technique is widely used in data processing and manipulation tasks, and it can help to improve the efficiency and readability of your code.

To understand the concept we will demonstrate to you using the old traditional method to write programs and what you can do using python list comprehension.

Example 1:

Using an old traditional way find the square of numbers in python.

# Traditional way
nums = list(range(1,5))
squares = []
for x in nums:
 squares.append(x ** 2)
 print(squares) 

Using List Comprehension find the square of numbers in python.

# creates a list from range 1 to 5
nums = list(range(1,5))
squares = [x ** 2 for x in nums]
print(squares) 

Example 2:

Find the even and odd numbers from 1 to 10 using old traditional way

# creates a list from range 1 to 10
nums = list(range(10))
even = []
odd = [] 
for i in nums:
 if i%2 == 0:
   even.append(i)
  else:
   odd.append(i)
print("Even Numbers: ", even)
print("Odd Numbers : ", odd) 

Find the even and odd numbers from 1 to 10 using List Comprehension

nums = list(range(10))
even = [x for x in nums if x%2 == 0]
odd = [x for x in nums if x%2 != 0]
print("Even Numbers: ", even)
print("Odd Numbers : ", odd) 

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App