Python 05

Python Lists (Arrays)

What would you do if you wanted to describe the days of the week or fruits that you love?

# ❌ wrong example
fruits = "🍎"
fruits = "🍊"
fruits = "🍌"

That might not be a great idea, but how about fruits = "🍎", "🍊", "🍌" or days_of_week = "Mon, Tues, Wed, ..." This will not work either. Instead, we have an option for the list.

months = ["Jan", "Feb", "Mar", "Apr", "May"]
fruits = ["🍎", "🍊", "🍌"]

If you know JavaScript, this will be familiar as an array. This list requires [] square brackets and fills the inside with the data types.

Python methods

Python has data types like string and int. Methods are the functions that bond to the data types.

print("Hello world") # function
name = "Luis"
print(name)
name.upper() # method
print(name)

Can you see the difference? Python data types have built-in functions that allow developers to use them.

Check out the documentation if you are interested. > https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str

To try methods, write the data type and put . next to it, and you will see the available methods.

Alt text

❗methods are connected to the data type, so they cannot be used by themselves. print() and int() are functions, not methods.

name = "Philip"

print(name.capitalize()) # βœ…

print(capitalize()) # ❌

List .append()

Let’s go back to our list.

half_year = ["Jan", "Feb", "Mar", "Apr", "May"]
fruits = ["🍎", "🍊", "🍌"]

If you want to add something to your list, use the .append() method.

print(half_year)
print(fruits)
half_year.append("June")
fruits.append("🍈")
print(half_year)
print(fruits)

Alt text

It appended June and melon to the lists!

Indexing

Now, you may want to use the items on the list. But print(fruits) returns the whole list. That is where Python indexing comes in.

fruits = ["🍎", "🍊", "🍌", "🍈"]
# To get banana
print(fruits[2])
# To get orange
print(fruits[1])
# To get an apple
print(fruits[0])
# To get the last item on the list
print(fruits[-1])

As you can check with the example above, indexing is a way to refer individual items from the list by their position.

❗Caution: indexing starts with 0, not 1 in programming. If you want to get the list’s first item, list[0] is correct.

my_list = ["first", "second", "third", "fourth", "last"]
0 1 2 3 4 ... πŸ‘‰ # index 0 to ...
# my_list[0] == "first"
-4 -3 -2 -1 ... πŸ‘ˆ # index -1 to ...
# my_list[-1] == "last"

List can contain all the data types we have learned previously.

my_list = [1, 2, 3, "first", "second", "third", [11, 22, 33, ["Hi I'm nested list", "hello"]], True, False]

Slicing

We learned how to get the individual item from the list. But what if you want multiple items? The answer is slicing.

fruits = ["πŸš—", "🍊", "🍌", "🍈", "🍹"]

Let’s bring our fruits list again. There are some items that are not fruit. To get only fruits, do this.

fruits = ["πŸš—", "🍊", "🍌", "🍈", "🍹"]
print(fruits[1:4])
"""
>> result should be ['🍊', '🍌', '🍈']
"""

There are a couple of things you need to check.

fruits[1:4]

The first number, 1, is where you want to start slicing. The second number, 4, is where you want to stop slicing.

fruits = ["🍎", "🍊", "🍌", "🍈", "🍹"]
print(fruits[0:4])

If our fruits list contains an apple, the slicing would start at 0. It is a bit confusing, but it is helpful.

Another thing we need to know about slicing is how we can reverse the list.

fruits = ["🍎", "🍊", "🍌", "🍈", "🍹"]
print(fruits[0:4:1])

Same as we do for slicing, add one more column, and that will decide the reading direction and step. For example, fruits[0:5:2] will return ['🍎', '🍌', '🍹']

fruits = ["🍎", "🍊", "🍌", "🍈", "🍹"]
print(fruits[0:4:1]) # 1 is default
print(frutis[0:5:2]) # `['🍎', '🍌', '🍹']`
print(fruits[::-1])
# returns ['🍹', '🍈', '🍌', '🍊', '🍎']

For the last print, we didn’t write anything for the start and stop values but the step. As you can see the result, it reverses the list because the step value has changed to -1.

Try a couple more slices to familiarize yourself with slice and reverse.

print(fruits[::-2])
print(fruits[1::-1])
print(fruits[:-3:-1])
print(fruits[-3::-1])
Toggle Answer πŸ‘‡

Alt text

Tuples

Mutable / Immutable

Before we dive into tuples, we need to step back for mutable and immutable.

days = ("Monday", "Tuesday", "Wednesday")
fruits = ["🍎", "🍊", "🍌", "🍈"]

As you know, the’ list’ comes in if we want to use some ordered sequence of values. But what if we want the list but want to keep the value the same?

days = ("Monday", "Tuesday", "Wednesday")
days. # check this in your terminal

❗To summarize, mutable means you can modify the value after you create the data, and immutable means you cannot modify the data.

Tuple

The tuple is a list but cannot modify values inside. Remember, if we put . after the data types, we can see the methods? Same as list, tuple has methods but cannot .append() or .pop().

Alt text

The same point with the list is indexing, which is the way of reading items in the list/tuple.

Categories:

Updated:

Comments