Article by: Manish Methani
Published on: October 5, 2021 at 2:04pm
6 min 56 sec read
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.
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.
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) # Output: 1 print(my_list) # 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
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 = "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".
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 print(my_list) # Output: [1, 2, 4]
# 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, ls, ls) # 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)
# 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, ls, ls) # 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)
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)
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 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.
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)
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)
Your go-to place to discover the Software Products, latest Tech News and Coding. Ignite Ideas, Unleash Innovation!
tech. 3 min 10 sec
Discover the Amazfit Balance: Redefining Wearable Technology in India with Advanced Health Monitoring, Sleek Design, and Smart Features. Elevate your fitness journey with this stylish, feature-rich smartwatch.
tech. 7 min 45 sec read
Discover the ultimate guide to the top smartwatches under 5000! Explore our curated selection, find the perfect fit for your needs, and elevate your tech game affordably. Dive into our top picks today!
tech. 1 min 54 sec read
Explore the intriguing hints and unravel the Quordle challenge for December 2, 2023! Decode the clues presented and discover the hidden solutions step by step.
tech. 4 min 7 sec read
Discover top apps & games at Apple 2023 App Store Awards, reshaping tech & entertainment!
tech. 2 min 41 sec read
Meet Amazon Q, the intelligent AI assistant designed for your workplace needs. Tailored to your business, it streamlines tasks, offers personalized advice, and boosts productivity. Learn how this smart tool transforms work efficiency!
tech. 1 min 49 sec read
Dive into the mind-teasing Quordle puzzle of November 29! Follow along on this word clue adventure, revealing the answers step by step. Engage your guessing skills!
tech. 19 min 19 sec read
Explore top-rated 43-inch smart TVs under Rs. 30,000 in India! Discover budget-friendly options offering brilliant visuals, seamless connectivity, and smart features for immersive entertainment. Find the perfect TV that fits your needs and enhances your viewing experience.
tech. 12 mins read
Explore the top picks for budget-friendly entertainment in India with the best 43-inch smart TVs priced under ₹15,000! Dive into vibrant displays, seamless connectivity, and impressive features, all at an affordable price point. Elevate your viewing experience affordably with these fantastic options!
tech. 10 min 44 sec read
Discover mind-blowing Cyber Monday Printer Deals that promise to redefine your printing experience! Get ready for amazing offers that will transform how you print and elevate your tech game.
tech. 1 min 52 sec read
Uncover the Quordle answers for November 28, 2023! Explore the hints and solutions provided for an exciting journey through the clues. Find out the solutions to todays Quordle puzzle right here!
tech. 14 min 47 sec read
Explore the best Cyber Monday HP deals on laptops that suit every need! From cutting-edge specs to reliable and stylish options, discover amazing discounts that elevate your tech game.
tech. 11 min 17 sec read
Discover unbelievable Cyber Monday camera deals you simply cannot overlook this year! From top-notch DSLRs to cutting-edge mirrorless cameras, seize the perfect opportunity to capture unforgettable moments. Hurry, these unbeatable offers wont last long!
tech. 23 min 42 sec read
Explore unbeatable Cyber Monday deals on trail cameras and accessories, perfect for outdoor enthusiasts! Dont miss out on these must-have offers designed to elevate your outdoor adventures and wildlife monitoring. Grab the best deals and gear up for your next outdoor escapade!
tech. 1 min 43 sec
Uncover the Quordle answers for November 27, 2023! Explore the clues and solutions to the days Quordle hints in this engaging puzzle adventure.
tech. 7 min 33 sec
Uncover exclusive Cyber Monday deals on PS5 controllers in 2023! Dont miss out on these must-grab offers, elevating your gaming experience. Explore deals you wont want to pass up!
tech. 4 min 34 sec
Explore Cyber Monday laptop deals under $400! Discover budget-friendly options with exceptional specs. Elevate your tech game affordably!
tech. 2 min 1 sec read
Dive into the mind-teasing Quordle puzzle of November 26! Follow along on this word clue adventure, revealing the answers step by step. Engage your guessing skills!
tech. 22 min 17 sec read
Discover unbeatable Black Friday tech deals on Amazon! Explore discounts on gadgets, phones, and smart devices for ultimate savings and upgrades.
tech. 13 min 57 sec read
Explore exclusive Black Friday deals on Nintendo Switch consoles, game bundles, and accessories. Discover top discounts to elevate your gaming experience.
tech. 8 min 24 sec read
Explore exclusive Black Friday 2023 deals on premium binoculars! Elevate outdoor adventures with amazing discounts on top-quality optics for nature enthusiasts and keen observers.
tech. 3 min 7 sec read
Discover the game-changing upgrade: OpenAI ChatGPT Voice feature now accessible to all users! Explore this innovative advancement in AI interaction, transforming conversations with your AI assistant for a more engaging experience.
tech. 4 min 52 sec read
Discover the Garmin Vivoactive 5, your ultimate fitness companion offering exclusive pricing deals. Explore its advanced features, health monitoring, GPS, music playback, and stylish design for an unparalleled fitness experience.
tech. 13 min 21 sec
Unsure between Fitbit Sense 2 and Versa 4? Our comprehensive comparison guides your purchase decision! Explore features, benefits, and potential Black Friday Deals 2023 to make an informed choice for your fitness journey.
tech. 2 min 17 sec
Delve into Qualcomm revolutionary AI-powered Snapdragon 7 Gen 3 chip, redefining mobile technology with its innovative advancements and incredible capabilities.
tech. 8 min 38 sec read
Discover the top call routing software for 2024. Streamline customer engagement with efficient solutions. Compare features, benefits, and find your ideal platform.
tech. 6 min 57 sec
Explore exclusive Black Friday deals on gaming laptops powered by NVIDIA GeForce! Elevate your gaming experience with these incredible offers, featuring cutting-edge technology and performance. Do not miss out on the chance to score big on NVIDIA GeForce laptops this Black Friday!
tech. 5 min 1 sec
Discover Microsoft Loop, a transformative platform redefining collaborative teamwork. Explore its canvas for seamless co-creation and synchronized components across diverse tools and devices.
tech. 2 min 36 sec
Discover todays Quordle solutions and intriguing hints for November 18, 2023. Unveil the answers while exploring captivating clues and unraveling the mystery of Quordle hints. Dive in for a thrilling word puzzle adventure!
tech. 5 min 6 sec read
Discover the Super Mario RPG Remake, set for release on November 17 exclusively for Nintendo Switch. Unveil revamped graphics, exciting battle mechanics, and nostalgic adventures for all gamers.
tech. 5 min 41 sec read
Unlock massive savings on PS5 consoles, games, and accessories this Black Friday! Explore exclusive discounts and unbeatable deals to elevate your gaming experience.
tech. 2 min 22 sec
Stay informed! YouTube now mandates creators to disclose AI elements in videos. Learn more about the platforms push for transparency in content creation.
tech. 2 min 56 sec
Snapchats collaboration with Amazon brings seamless shopping to the app! Explore and buy Amazon products directly on Snapchat. Discover a new way to shop effortlessly within the social platform.
tech. 2 min 42 se
Discover the future of wearable tech with Humane AI Pin! Packed with innovative features like gesture control and a miniature projector, this groundbreaking gadget redefines how you interact with AI. Pre-orders start November 16!
tech. 2 min 16 sec
Discover a smarter way to shop online with Microsoft Edge! Introducing Review Summaries for quick insights and Copilot, your personalized shopping buddy. Simplify decisions, enjoy tailored recommendations, and experience a new level of digital convenience!
tech. 3 min 10 sec
Discover the top web hosting providers for 2024! From trusted names like Bluehost to performance-driven options like SiteGround and budget-friendly Hostinger, find the perfect solution for your online needs. Elevate your digital presence now!
tech. 3 min 16 sec
Dive into the future of AI conversations with ChatGPT! Explore a world where ChatGPT not only understands your words but sees, hears, and speaks. Unleash a new era of interactive and engaging dialogues. Discover the magic of multi-modal interactions today!
tech. 2 min 55 sec read
Rev up your driving experience with JioMotive! 🚗💨 Transform any car into a smart vehicle with real-time tracking, geofencing, and intelligent insights.
tech. 2 min 24 sec read
Uncover the essential toolkit for a successful web development journey! From Visual Studio Code to Angular, we have got the top 12 tools that will make your coding adventure epic. Dive into this engaging guide and supercharge your skills now
tech. 3 min 48 sec read
Google Alert: Secure Your Account Now! Do not Miss Out on Essential Tips!
tech. 2 min 35 sec
Upgrade your chats with WhatsApps new text tools! From cool coding tricks to easy quoting, your messages just got a makeover. Discover the fun in texting with these exciting features!
tech. 2 min 43 sec
Explore 6 exciting IT careers without an engineering degree! From coding to data insights, discover your path in tech. Passion over paperwork!
tech. 2 min 30 sec read
Unlock the future of phones with Samsung Galaxy AI! Experience the magic of AI Live Translate Call and break language barriers. Your phone is about to get smarter than ever!
tech. 2 min 6 sec read
Dive into the ultimate face-off between Elon Musks rebellious
tech. 1 min 45 sec
Unlock GATE success with NPTELs game-changing portal! Join 50,700+ students on the journey to acing the GATE exam. Dive into free resources, ace mock tests, and conquer your GATE goals! 🚀📚 #NPTEL #GATEExam #SuccessJourney
tech. 2 min 4 sec
Say goodbye to snoopy eyes! 🕵️ WhatsApp got your back with the new
tech. 1 min 58 sec read
Optimize your site on the go! Discover the Bing Webmaster Tools Android App—your SEO toolkit for managing site performance, fixing issues, and enhancing visibility in Bing searches. Download now on Google Play for a seamless mobile SEO experience.
tech. 4 min 10 sec read
Unlock your coding potential with Apple Swift Student Challenge 2024! Explore the new Distinguished Winners category, exclusive rewards, and a chance to shine at Apples HQ. Learn more about eligibility and how to participate. Dont miss this exciting opportunity for student developers!
tech. 6 min 17 sec read
Explore OpenAIs groundbreaking GPTs: Custom AI chatbots made easy. Create personalized AI models without coding. Unleash the power of GPT OpenAI with user-friendly customization.
tech. 5 min 23 sec
Discover the best moveset for Virizion in Pokémon Go and explore its prominence in the Ultra and Master Leagues. Get insights on its moves, strengths, and tips for battling in the Pokémon Go world.
tech. 5 min 5 sec
Save Big on Luxe, Inspire 2, Sense 2, and More - Exclusive Offers Inside!
tech. 6 min 23 sec
Uncover the captivating world of The Legend of Zelda, a legendary video game series enriched by Shigeru Miyamotos influence. Explore Amazon for games and collectibles, learn about Black Friday Nintendo Switch deals, and the quest for a live-action adaptation. Dive into the enchanting realm of Hyrule and embark on a gaming adventure like no other.
Codzify opens the door to a wealth of programming videos, free courses, mock tests, and endless opportunities for learning. Join us today and let your coding journey begin!Start for Free. Login Now!
Explore Coding in Simplified Way with Codzify.com
Online Coding Courses