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 |
Slicing the complete list will perform a copy:
len()
enumerate()
zip()
(Optional)in
and not in
operatorsThe 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:
index()
MethodThe index
method allows you to find the index of a value by passing its name:
append()
append
adds an element to the end of a list
:
insert()
insert
adds an element to a list
at a given position:
del
del
removes an item using the index:
remove()
remove
removes an item with using actual value of it:
:bulb: If the value appears multiple times in the list, only the first instance of the value will be removed.
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:
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:
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:
:bulb: Note that most of the time method will modify list
in place, while function will create a new list
:bulb: 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.
list()
and tuple()
[]
) used to access elements in a container by index.