Question about Indexing

Screen Link:

My Code:

import pandas as pd
titanic = pd.read_csv('train.csv')
cols = ['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
titanic = titanic[cols].dropna()

When indexing the columns, I thought the only way to change the columns was to do
titanic.columns = ['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] ??

How come this way works? How does the Python know that the columns are matched with the original?
cols = ['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']

Yes that is one way to change dataframe column names.

Here you are not changing column names of dataframe. This is just a list. (This statement will not affect dataframe anyway.) Here you are storing column names in cols variable. It has nothing to do with titanic dataframe.

The original dataframe raw_titanic has following columns:
print(raw_titanic.columns)

Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')

We are selecting a list of columns and assigning it to cols variable.
cols = ['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
Next, we are selecting these columns from raw_titanic, assigning the result to a new dataframe titanic.

titanic = raw_titanic[['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']]

Note the double brackets here ([[]]), which is similar to

titanic = raw_titanic[:, ['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']]