Introduction
For everything in life, there are building blocks, and to fully understand a concept, we usually have to go down to those basics.
Python has building blocks that we’re going to dive into in this article.
Lists
A list is an ordered, mutable collection of items. They can hold different data types.
Characteristics of Lists
- They are ordered.
- They can be changed (mutable).
- They can hold different data types.
- They can be indexed.
- They are stored in square brackets [ ].
- They accept duplicate elements.
Indexing
Items in a list can be accessed using a method called indexing.
Indexes, in this context, are numbers assigned to the items in a list. The items are indexed/numbered starting from 0.
An example would be:
To fetch items, we write:
Positive indexing: This is simply calling items with their natural index numbers.
Negative indexing: Negative indexing works backward. If you want to pick the -4 item, you count from right to left starting from 1.
This could be useful when you have a long list and want to access the second-to-last item. For instance, writing -2 would do that.
Slicing indexing: Slicing allows us to pick a group of items. When slicing, you need two indexes—the index to start slicing from and the index to end at. However, the ending index is not included in the result.
As we see in the example below, print(a_list[1:4]) prints items at index 1 to 3. Index 4 (Tolu) is excluded.
We can also slice like this: print(a_list[:3]). This asks Python to return the values from the beginning up to index 2, as index 3 is excluded.
Skipping indexing: As the name implies, skipping indexing allows us to skip items we do not want. In a list of numbers, skip indexing can give us only even numbers.
Mutability of lists
As we’ve mentioned earlier, lists are mutable. We can update them and delete items from them.
Tuples
A tuple is an immutable and ordered collection of elements.
Characteristics of Tuples
- They are ordered.
- They are unchangeable (immutable).
- They can hold different data types.
- They can be indexed.
- They are stored in curved brackets ().
- They accept duplicate elements.
- They are faster than lists because they are immutable.
Example of Tuples
Tuples share the same indexing style as Lists.
Immutability of Tuples: They cannot be deleted or updated.
Dictionaries
A dictionary is an unordered, mutable collection of key-value pairs.
Characteristics of Dictionaries
- They are unordered.
- They can be changed (mutable).
- They can hold different data types.
- They are indexed not by position but by keys.
- They are stored in curly brackets {}.
- They accept duplicate value elements.
- Keys must be unique.
Example of a dictionary
To retrieve values, we use the keys. In this case, the keys are: name, age, gender, country, friend.
To update, you assign a new value using an equals sign (=).
Source link
lol