<< Back to PYTHON
Python List Examples
Store elements in a dynamically-sized list. Append to, remove from and loop over lists.List. Consider this—time itself may be a list. Fossils tell us of great creatures that roamed millions of years ago. They no longer exist.
List details. Elements can be added, looped over or sorted. Lists can be combined with other structures. Each day adds another element to the list of time.
String List
First example. A list manages its capacity. The order is guaranteed in a list, unlike in a dictionary. A list is an ordered collection.
Step 1: We create an empty list. A list can start empty, but will expand to fit elements as we add them.
Step 2: We call append() 4 times. The 4 elements we add to the list are stored in that order.
Python program that uses append
# Step 1: create empty list.
list = []
# Step 2: append 4 numbers to the list.
list.append(1)
list.append(2)
list.append(6)
list.append(3)
print(list)
Output
[1, 2, 6, 3]
Insert. An element can be added anywhere in a list. With insert() we can add to the first part or somewhere in the middle of the list.
Important: The index 1 indicates the second element location. Lists are indexed starting at zero—they are zero-based.
Python program that calls insert
list = ["dot", "Codex"]
# Insert at index 1.
list.insert(1, "net")
print(list)
Output
['dot', 'net', 'Codex']
Extend. A list can be appended to another list with extend(). So we extend one list to include another list at its end. We concatenate (combine) lists.
Caution: If we try to call append() to add a list, the entire new list will be added as a single element of the result list.
Tip: Another option is to use a for-loop, or use the range syntax to concatenate (extend) the list.
Python program that uses extend
# Two lists.
a = [1, 2, 3]
b = [4, 5, 6]
# Add all elements in list "b" to list "a."
a.extend(b)
# List "a" now contains six elements.
print(a)
Output
[1, 2, 3, 4, 5, 6]
Len. A list contains a certain number of elements. This may be zero if it is empty. With len, a built-in method, we access the element count.
Python program that uses len
animals = []
animals.append("cat")
animals.append("dog")
count = len(animals)
# Display the list and the length.
print(animals)
print(count)
Output
['cat', 'dog']
2
In keyword. Is an element in a list? We use "in" and "not in" to determine this. Other approaches are possible but "in" is simplest. Here we search a list with "in" and "not in."
InPython program that uses in
items = ["book", "computer", "keys", "mug"]
if "computer" in items:
print(1)
if "atlas" in items:
# This is not reached.
print(2)
else:
print(3)
if "marker" not in items:
print(4)
Output
1
3
4
Sort, reverse. Lists maintain the order of their elements. And they can be reordered. With the sort method, we change the order of elements from low to high.
And: With reverse, we invert the current order of the elements. Sort and reverse can be combined (for a reversed sort).
Python program that sorts and reverses
list = [400, 500, 100, 2000]
# Reversed.
list.reverse()
print(list)
# Sorted.
list.sort()
print(list)
# Sorted and reversed.
list.reverse()
print(list)
Output
[2000, 100, 500, 400]
[100, 400, 500, 2000]
[2000, 500, 400, 100]
Sort, key. Sometimes elements in a list must be sorted in a specific way. Here, we sort list string elements based on their last characters, and then their second characters.
Def: The example first uses a def method as the key argument to sort. The "key equals" part must be specified.
Lambda: We introduce an alternate syntax form, the lambda expression, for sorting elements in a last. This targets the second char.
LambdaPython program that sorts with def, lambda
def lastchar(s):
# Return last character in string.
return s[-1]
# Input.
values = ["abc", "bca", "cab"]
# Sort by last character in the strings.
values.sort(key=lastchar)
print(values)
# Sort by the second character in the strings.
# ... Use a lambda expression.
values.sort(key=lambda s: s[1])
print(values)
Output
['bca', 'cab', 'abc']
['cab', 'abc', 'bca']
Remove, del. Remove acts upon a value. It first searches for that value, and then removes it. Elements (at an index) can also be removed with the del statement.
Remove: This takes away the first matching element in the list. We can call it multiple times, and it could keep changing the list.
Del: This meanwhile removes elements by index, or a range of indices. Del uses the slice syntax.
DelPython program that removes elements
names = ["Tommy", "Bill", "Janet", "Bill", "Stacy"]
# Remove this value.
names.remove("Bill")
print(names)
# Delete all except first two elements.
del names[2:]
print(names)
# Delete all except last element.
del names[:1]
print(names)
Output
['Tommy', 'Janet', 'Bill', 'Stacy']
['Tommy', 'Janet']
['Janet']
For-loop. In list loops, we often need no index. We require just the elements in order. The for-loop is ideal in this situation. It eliminates the confusion of an index variable.
Here: We encounter each of the four list elements in the for-loop. We use the identifier "element" in the loop body.
Python program that uses for, list
# An input list.
elements = ["spider", "moth", "butterfly", "lizard"]
# Use simple for-loop.
for element in elements:
print(element)
Output
spider
moth
butterfly
lizard
Adjacent elements. Often we need only one element as we loop. But in some cases, we need adjacent elements to compare. Here we access adjacent elements in the list.
Tip: Starting at index 1 is key. In the loop body, we access the previous element, at index "i - 1", and the current element.
Python program that gets adjacent list elements
# Input list.
elements = [0, 10, 20, 30]
# Use range.
for i in range(1, len(elements)):
# Get two adjacent elements.
a = elements[i - 1]
b = elements[i]
# Print two elements.
print(a, b)
Output
0 10
10 20
20 30
List comprehension. This syntax in Python expresses an entire loop in a single statement. In this example we use list comprehension to create a list of HTML strings.
Program: We apply the html method on each string in the input list. This calls capitalize() and returns an HTML fragment.
Identifier: In this list comprehension, each string is given the identifier "x." Html() is called on each element in the list.
Info: In list comprehension, we apply a method to each element. The syntax is short, making it easier to read.
List ComprehensionPython program that uses list comprehension
# Transform string into HTML.
def html(s):
return "<b>" + s.capitalize() + "</b>"
# Input string.
input = ["rabbit", "mouse", "gorilla", "giraffe"]
# List comprehension.
list = [html(x) for x in input]
# Result list.
print(list)
Output
['<b>Rabbit</b>', '<b>Mouse</b>', '<b>Gorilla</b>', '<b>Giraffe</b>']
File lines. Here we read a file's lines into a list. Often each line needs to be stripped of trailing whitespace and newlines. We use a loop to strip each line and append it to a list.
StripResult: The ending list has no trailing newlines at the end of the string elements.
Python program that uses readlines, list
list = []
f = open("C:\\programs\\file.txt", "r")
# Loop through all lines.
for line in f.readlines():
# Strip each line to remove trailing newline.
list.append(line.strip())
print(list)
Input file
Line 1.
Line 2.
Output
['Line 1.', 'Line 2.']
Copy. A list is copied using the slice syntax. When we specify no numbers in the slice, it covers the entire list. So by assigning to an unspecified slice, we copy the list.
Copy ListImportant: This program shows that the copied list (list2) has its own memory region. When we modify it, the original is not changed.
Resize: We can also resize a list. The slice syntax, and methods like append() are useful here.
Resize ListPython program that copies list
list1 = [100, 200, 300]
# Make a copy of list 1 and store it in list 2.
list2 = list1[:]
# Modify list 2.
list2[0] = -1
# The lists are separate.
print("LIST: ", list1)
print("COPIED LIST:", list2)
Output
LIST: [100, 200, 300]
COPIED LIST: [-1, 200, 300]
Format. Suppose we have a list. We want to insert some elements from it into a string. We can use str.format for this. Format() has special support for list arguments.
Tip: The second argument of format() assigns an identifier to a list variable, and we can access elements within the string.
Python program that uses format, list
list = [10, 20, 30]
# Use "v" identifier to refer to the list.
# ... Access its elements in format.
res = str.format("The values are {v[0]}, {v[1]} and {v[2]}", v=list)
print(res)
Output
The values are 10, 20 and 30
All built-in. With all, we check to see if all elements evaluate to True. If even a single element is false, all() returns False. The method uses standard boolean evaluation for elements.
Python program that uses all
items = [False, None, True]
# Some elements evaluate to False, so all is False.
if not all(items):
print(False)
items = [10, 20, 30]
# All the items evaluate to True.
if all(items):
print(True)
Output
False
True
Any built-in. This loops over its iterable argument (like a list). If "any" of the elements in the argument evaluate to True, any() too returns True. So it scans for a True result.
anyFalse: Any() returns False if no elements are True. So "not any" is the same as "no True values."
Python program that uses any
elements = [False, None, "Pomegranate", 0]
# One value is True, so any returns True.
if any(elements):
print(True)
elements = [0, 0, False]
# Now no elements are True.
# ... Any returns False.
if not any(elements):
print(False)
Output
True
False
Duplicates. Sometimes we want to remove duplicate elements from a list. If ordering is important, we may need a special method to avoid reordering elements. Here a set is useful.
Duplicates
Two-dimensional. A list can contain other lists. We can use this kind of data structure as a two-dimensional grid of elements. These are jagged. Sub-lists can vary in length.
2D ListTip: Lists of lists can be useful for small graphs and other applications that need a coordinate lookup, but not a huge memory space.
Warning: A 2D list is not efficient for larger areas. An array would be faster and use far less memory.
Index, count. With the index method, we can search a list. And with count, we can sum up the number of instances of an element within the list (count could be implemented with index).
IndexArray. In Python a list is separate from an array. Lists are good for small data sets, but for larger amounts of data, arrays are far more efficient. They often use 90% less memory.
ArrayA summary. A list stores elements one after another, in a linear collection. In Python it handles any type of element, including numbers, strings—even tuples and other collections.
Related Links:
- Python global and nonlocal
- Python not: If Not True
- Python Convert Decimal Binary Octal and Hexadecimal
- Python Tkinter Scale
- Python Tkinter Scrollbar
- Python Tkinter Text
- Python History
- Python Number: random, float and divmod
- Python Tkinter Toplevel
- Python Tkinter Spinbox
- Python Tkinter PanedWindow
- Python Tkinter LabelFrame
- Python Tkinter MessageBox
- Python Website Blocker
- Python Console Programs: Input and Print
- Python Display Calendar
- Python Check Number Odd or Even
- Python readline Example: Read Next Line
- Python Anagram Find Method
- Python Any: Any Versus All, List Performance
- Python Filename With Date Example (date.today)
- Python Find String: index and count
- Python filter (Lambda Removes From List or Range)
- Python ASCII Value of Character
- Python Sum Example
- Python make simple Calculator
- Python Add Two Matrices
- Python Multiply Two Matrices
- Python SyntaxError (invalid syntax)
- Python Transpose Matrix
- Python Remove Punctuation from String
- Python Dictionary items() method with Examples
- Python Dictionary keys() method with Examples
- Python Textwrap Wrap Example
- Python Dictionary popitem() method with Examples
- Python Dictionary pop() method with Examples
- Python HTML: HTMLParser, Read Markup
- Python Tkinter Tutorial
- Python Array Examples
- Python ord, chr Built Ins
- Python Dictionary setdefault() method with Examples
- Python Dictionary update() method with Examples
- Python Dictionary values() method with Examples
- Python complex() function with Examples
- Python delattr() function with Examples
- Python dir() function with Examples
- Python divmod() function with Examples
- Python Loops
- Python for loop
- Python while loop
- Python enumerate() function with Examples
- Python break
- Python continue
- Python dict() function with Examples
- Python pass
- Python Strings
- Python Lists
- Python Tuples
- Python Sets
- Python Built-in Functions
- Python filter() function with Examples
- Python dict Keyword (Copy Dictionary)
- Python Dictionary Order Benchmark
- Python Dictionary String Key Performance
- Python 2D Array: Create 2D Array of Integers
- Python Divmod Examples, Modulo Operator
- bin() in Python | Python bin() Function with Examples
- Python Oops Concept
- Python Object Classes
- Python Constructors
- Python hash() function with Examples
- Python Pandas | Python Pandas Tutorial
- Python Class Examples: Init and Self
- Python help() function with Examples
- Python IndentationError (unexpected indent)
- Python Index and Count (Search List)
- Python min() function with Examples
- Python classmethod and staticmethod Use
- Python set() function with Examples
- Python hex() function with Examples
- Python id() function with Examples
- Python sorted() function with Examples
- Python next() function with Examples
- Python Compound Interest
- Python List insert() method with Examples
- Python Datetime Methods: Date, Timedelta
- Python setattr() function with Examples
- Python 2D List Examples
- Python Pandas Data operations
- Python Def Methods and Arguments (callable)
- Python slice() function with Examples
- Python Remove HTML Tags
- Python input() function with Examples
- Python enumerate (For Index, Element)
- Python Display the multiplication Table
- Python int() function with Examples
- Python Error: Try, Except and Raise
- Python isinstance() function with Examples
- Python oct() function with Examples
- Python startswith, endswith Examples
- Python List append() method with Examples
- Python NumPy Examples (array, random, arange)
- Python Replace Example
- Python List clear() method with Examples
- Python List copy() method with Examples
- Python Lower Dictionary: String Performance
- Python Lower and Upper: Capitalize String
- Python Dictionary Examples
- Python map Examples
- Python Len (String Length)
- Python Padding Examples: ljust, rjust
- Python Type: setattr and getattr Examples
- Python String List Examples
- Python String
- Python Remove Duplicates From List
- Python If Examples: Elif, Else
- Python Programs | Python Programming Examples
- Python List count() method with Examples
- Python List extend() method with Examples
- Python List index() method with Examples
- Python List pop() method with Examples
- Python Palindrome Method: Detect Words, Sentences
- Python Path: os.path Examples
- Python List remove() method with Examples
- Python List reverse() method with Examples
- Top 50+ Python Interview Questions (2021)
- Python List sort() method with Examples
- Python sort word in Alphabetic Order
- abs() in Python | Python abs() Function with Examples
- Python String | encode() method with Examples
- all() in Python | Python all() Function with Examples
- any() in Python | Python any() Function with Examples
- Python Built In Functions
- ascii() in Python | Python ascii() Function with Examples
- Python bytes, bytearray Examples (memoryview)
- bool() in Python | Python bool() Function with Examples
- bytearray() in Python | Python bytearray() Function with Examples
- Python Caesar Cipher
- bytes() in Python | Python bytes() Function with Examples
- Python Sum of Natural Numbers
- callable() in Python | Python callable() Function with Examples
- Python Set add() method with Examples
- Python Set discard() method with Examples
- Python Set pop() method with Examples
- Python math.floor, import math Examples
- Python Return Keyword (Return Multiple Values)
- Python while Loop Examples
- Python Math Examples
- Python Reverse String
- Python max, min Examples
- Python pass Statement
- Python Set remove() method with Examples
- Python Dictionary
- Python Functions
- Python String | capitalize() method with Examples
- Python String | casefold() method with Examples
- Python re.sub, subn Methods
- Python subprocess Examples: subprocess.run
- Python Tkinter Checkbutton
- Python Tkinter Entry
- Python String | center() method with Examples
- Python Substring Examples
- Python pow Example, Power Operator
- Python Lambda
- Python Files I/O
- Python Modules
- Python String | count() method with Examples
- Python String | endswith() method with Examples
- Python String | expandtabs() method with Examples
- Python Prime Number Method
- Python String | find() method with Examples
- Python String | format() method with Examples
- Python String | index() method with Examples
- Python String | isalnum() method with Examples
- Python String | isalpha() method with Examples
- Python String | isdecimal() method with Examples
- Python Pandas Sorting
- Python String | isdigit() method with Examples
- Python Convert Types
- Python String | isidentifier() method with Examples
- Python Pandas Add column to DataFrame columns
- Python String | islower() method with Examples
- Python Pandas Reading Files
- Python Right String Part
- Python IOError Fix, os.path.exists
- Python Punctuation and Whitespace (string.punctuation)
- Python isalnum: String Is Alphanumeric
- Python Pandas Series
- Python Pandas DataFrame
- Python Recursion Example
- Python ROT13 Method
- Python StringIO Examples and Benchmark
- Python Import Syntax Examples: Modules, NameError
- Python in Keyword
- Python iter Example: next
- Python Round Up and Down (Math Round)
- Python List Comprehension
- Python Collection Module
- Python Math Module
- Python OS Module
- Python Random Module
- Python Statistics Module
- Python String Equals: casefold
- Python Sys Module
- Top 10 Python IDEs | Python IDEs
- Python Arrays
- Python Magic Method
- Python Stack and Queue
- Python MySQL Environment Setup
- Python MySQL Database Connection
- Python MySQL Creating New Database
- Python MySQL Creating Tables
- Python Word Count Method (re.findall)
- Python String Literal: F, R Strings
- Python MySQL Update Operation
- Python MySQL Join Operation
- Python Armstrong Number
- Learn Python Tutorial
- Python Factorial Number using Recursion
- Python Features
- Python Comments
- Python if else
- Python Translate and Maketrans Examples
- Python Website Blocker | Building Python Script
- Python Itertools Module: Cycle and Repeat
- Python Operators
- Python Int Example
- Python join Example: Combine Strings From List
- Python Read CSV File
- Python Write CSV File
- Python Read Excel File
- Python Write Excel File
- Python json: Import JSON, load and dumps
- Python Lambda Expressions
- Python Print the Fibonacci sequence
- Python format Example (Format Literal)
- Python Namedtuple Example
- Python SciPy Tutorial
- Python Applications
- Python KeyError Fix: Use Dictionary get
- Python Resize List: Slice and Append
- Python String | translate() method with Examples
- Python Copy List (Slice Entire List)
- Python None: TypeError, NoneType Has No Length
- Python MySQL Performing Transactions
- Python String | isnumeric() method with Examples
- Python MongoDB Example
- Python String | isprintable() method with Examples
- Python Tkinter Canvas
- Python String | isspace() method with Examples
- Python Tkinter Frame
- Python Tkinter Label
- Python Tkinter Listbox
- Python String | istitle() method with Examples
- Python Website Blocker | Script Deployment on Linux
- Python Website Blocker | Script Deployment on Windows
- Python String | isupper() method with Examples
- Python String split() method with Examples
- Python Slice Examples: Start, Stop and Step
- Python String | join() method with Examples
- Python String | ljust() method with Examples
- Python Sort by File Size
- Python Arithmetic Operations
- Python String | lower() method with Examples
- Python Exception Handling | Python try except
- Python Date
- Python Regex | Regular Expression
- Python Sending Email using SMTP
- Python Command Line Arguments
- Python List Comprehension Examples
- Python Assert Keyword
- Python Set Examples
- Python Fibonacci Sequence
- Python Maze Pathfinding Example
- Python Memoize: Dictionary, functools.lru_cache
- Python Timeit, Repeat Examples
- Python Strip Examples
- Python asyncio Example: yield from asyncio.sleep
- Python String Between, Before and After Methods
- Python bool Use (Returns True or False)
- Python Counter Example
- Python frozenset: Immutable Sets
- Python Generator Examples: Yield, Expressions
- Python CSV: csv.reader and Sniffer
- Python globals, locals, vars and dir
- Python abs: Absolute Value
- Python gzip: Compression Examples
- Python Function Display Calendar
- Python Display Fibonacci Sequence Recursion
- Python String | lstrip() method with Examples
- Python del Operator (Remove at Index or Key)
- Python String | partition() method with Examples
- Python String | replace() method with Examples
- Python Zip Examples: Zip Objects
- Python String | rfind() method with Examples
- Python String | rindex() method with Examples
- Python String rjust() method with Examples
- Python String rpartition() method with Examples
- Python String rsplit() method with Examples
- Python Area Of Triangle
- Python Quadratic Equation
- Python swap two Variables
- Python Generate Random Number
- Python Convert Kilometers to Miles
- Python Convert Celsius to Fahrenheit
- Python Check Number Positive Negative or Zero
- Python Check Leap Year
- Python Check Prime Number
- Top 40 Python Pandas Interview Questions (2021)
- Python Check Armstrong Number
- Python SQLite Example
- Python Tkinter Button
- Python Find LCM
- Python Find HCF
- Python Tuple Examples
- Python String | rstrip() method with Examples
- Python String splitlines() method with Examples
- Python String | startswith() method with Examples
- Python String | swapcase() method with Examples
- Python Truncate String
- Python String | upper() method with Examples
- Python for: Loop Over String Characters
- Python String | zfill() method with Examples
- Python Sort Examples: Sorted List, Dictionary
- Python XML: Expat, StartElementHandler
- Python Urllib Usage: Urlopen, UrlParse
- Python File Handling (with open, write)
- Python Example
- Python variables
- Python Random Numbers: randint, random.choice
- Python assert, O Option
- Python Data Types
- Python keywords
- Python literals
- Python MySQL Insert Operation
- Python MySQL Read Operation
- Python ascii Example
- Python ASCII Table Generator: chr
- Python Range: For Loop, Create List From Range
- Python re.match Performance
- Python re.match, search Examples
- Python Tkinter Menubutton
- Python Tkinter Menu
- Python Tkinter Message
- Python Tkinter Radiobutton
- Python List Examples
- Python Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf