List Data Type in Depth
- We’ve touched data structure topic already several times (here, here, and here for example).
- We’ve talked about lists here too.
- And here we’ll go into depth.
- Usually contains homogeneous sequence of elements.
Lists Methods
append(x)
Adds an item to the end of the list.
</tbody> </table> ### `extend(iterable)` Extend the list by appending all the items from the iterable.append |
Alternative |
---|---|
|
|
extend |
Alternative |
---|---|
|
|
insert |
Alternative |
---|---|
|
|
remove |
Alternative |
---|---|
|
|
You can dictate your own rule on how to sort by using `key` argument
Here we are checking when the first letter is uppercase, and if it was, then our function returns true, otherwise naturally it'll be false. And since booleans in Python are implemented as a subclass of integers we get the cities with the first letter lowercase first and then capitalized cities.
cities = ["Tokyo", "hong Kong", "Berlin", "moscow", "Singapore"]
cities.sort(key=lambda x: x[0].isupper())
print(cities)
We can pass the len
function as key, the strings are sorted based on their length.
cities = ["Tokyo", "hong Kong", "Berlin", "moscow", "Singapore"]
cities.sort(key=len)
print(cities)
clear |
Alternative |
---|---|
|
|
Queues implementation with lists
print_documents = ["filename.pdf", "file2.pdf"]
print_documents.append("another-file.pdf")
first_document = print_documents.pop(0)
copy |
Alternative |
---|---|
|
|
Normal way | List comprehension way |
---|---|
|
Or make it a bit more cranky
|
|
|
|
|
Normal way | Nested list comprehensions way |
---|---|
Or
|
|