Lists are one of the 4 data types in Python used to store collections of data. A short comparison of the containers is shown below:
Feature |
List |
Tuple |
Dictionary |
Set |
Mutable (Can be modified in place) |
Yes |
No |
Yes (keys are immutable) |
Yes |
Iterable (Can be use in for loop) |
Yes |
Yes |
Yes |
Yes |
Ordered (Can access by index, slicing) |
Yes |
Yes |
No |
No |
Duplicate Values |
Allowed |
Allowed |
Not in keys |
Not allowed |
Lists
Getting values with indexes
Negative indexes
Getting sublists with Slices
Slicing the complete list will perform a copy:
Getting a list length with len()
Changing values with indexes
Concatenation and Replication
Using for loops with Lists
Getting the index in a loop with enumerate()
Loop in Multiple Lists with zip()
(Optional)
The in
and not in
operators
The Multiple Assignment (Unpacking) Trick
The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:
You could type this line of code:
The multiple assignment trick can also be used to swap the values in two variables:
The index()
Method
The index
method allows you to find the index of a value by passing its name:
Adding Values
append()
append
adds an element to the end of a list
:
insert()
insert
adds an element to a list
at a given position:
Removing Values
del
del
removes an item using the index:
remove()
remove
removes an item with using actual value of it:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
If the value appears multiple times in the list, only the first instance of the value will be removed.
Sorting values with sort()
You can also pass True
for the reverse
keyword argument to have sort()
sort the values in reverse order:
By default, string are sorted using ASCII order and if you need to sort the values in regular alphabetical order, pass str.lower
for the key keyword argument in the sort()
method call:
You can use the built-in function sorted
to return a new list:
Numerical functions
There are a number of built-in functions that can be used on lists
that allow you to quickly look through a list
without writing your own loops:
List Comprehensions are a special kind of syntax that let us create lists out of other lists, and are incredibly useful when dealing with numbers and with one or two levels of nested for loops.
This is how we create a new list from an existing collection with a For Loop:
And this is how we do the same with a List Comprehension:
We can do the same with numbers:
Adding conditionals
If we want new_list
to have only the names that start with C, with a for loop, we would do it like this:
In a List Comprehension, we add the if
statement at the end:
To use an if-else
statement in a List Comprehension:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Note that most of the time method will modify list
in place, while function will create a new list
Tuples
The Tuple data type
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
The key difference between tuples and lists is that, while tuples
are immutable objects, lists
are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
The main way that tuples are different from lists is that tuples, like strings, are immutable.
Converting between list()
and tuple()
Keywords
- containers (容器): Structures that hold or organize multiple values, such as lists, tuples, and strings.
- methods (方法): Functions that are associated with an object and can be called on that object.
- sequence (序列): An ordered collection of items, where each item can be accessed by its position (index).
- list (串列): A mutable sequence type in Python that can store a collection of items with different data types.
- tuple (元組): An immutable sequence type in Python that can store a collection of items with different data types.
- elements (元素): The individual items or values contained within a container like a list or tuple.
- index (索引): The numerical position of an element within a sequence, starting from 0.
- subscript operator (下標運算子): The square brackets (
[]
) used to access elements in a container by index.
- slicing (切片): A method to retrieve a subset of a sequence by specifying a start, stop, and optionally a step.
- mutable (可變的): Describes an object that can be changed after it is created, like a list.
- item assignment (元素賦值): The process of changing the value of an element within a mutable container using its index.
- iteration by item (逐項迭代): The process of going through each element in a container one at a time.
- list comprehension (串列生成式): A concise way to create lists by applying an expression to each item in a sequence.
- immutable (不可變的): Describes an object that cannot be changed after it is created, like a tuple or string.
- reference (參照): A variable in Python stores a reference, which is the memory address of an object. It points to where the object is stored rather than containing the object itself.
- modify in-place (原地修改): Changing the content of a mutable object without creating a new object.