Lecture: Learning Python 3-Lists and Comprehensions ver. 6

Last Updated on July 9, 2022 by shibatau

The link to Python 6-If Statements is added.

I. What will you learn?

These posts are Python tutorials for beginners and used for my lectures.

Learning Python 0-Cheat Sheets

Learning Python 1-Google Colaboratory

Learning Python 2-Sample data

Learning Python 3-Lists and Comprehensions

Learning Python 4-Dictionaries and Data frames

Learning Python 5-Functions

Learning Python 6-If Statements

Learning Python 7-For Loops

Learning Python 8-Classes and Objects

II. Lists

Characteristics of Lists:

  • The lists are mutable.
  • A list can store objects of any type.
  • The lists are ordered.
  • The element of the list can accessed by index.

See Cheat Sheets Basics IV. DATA STRUCTURES 1. LIST.

You can see the scripts here:

https://colab.research.google.com/drive/1X5K7x7wsuRruhPo2NmxWAM74-Exb03hw?usp=sharing

III. Comprehensions

See Cheat Sheets Basics VI COMPREHENSIONS 1, 2.

List comprehensions offer a shorter syntax when you want to create a new list based on the values of an existing list. It is syntactic sugar that makes code easier to read and write.

1. List comprehensions
ls0 = [1, 2, 3, 4, 5]
[item*2 for item in ls0]
[item*2 for item in range(1, 6)]
# Using For Loops
ls1 = []
for item in ls0:
    ls1.append(item*2)
ls1
# [2, 4, 6, 8, 10]
[item for item in ls0 if item%2==0]
# [2, 4]
2. Dictionary comprehensions
dic = {'Alex': 30, 'Bob': 40, 'Carol': 50}
[itemk for itemk, itemv in dic.items() if itemv >= 40]
# ['Bob', 'Carol']

You can see the scripts here:

https://colab.research.google.com/drive/1J6l72PcDfBXMg7alpm5U5-bxJXkl9a5X?usp=sharing

About shibatau

I was born and grown up in Kyoto. I studied western philosophy at the University and specialized in analytic philosophy, especially Ludwig Wittgenstein at the postgraduate school. I'm interested in new technology, especially machine learning and have been learning R language for two years and began to learn Python last summer. Listening toParamore, Sia, Amazarashi and MIyuki Nakajima. Favorite movies I've recently seen: "FREEHELD". Favorite actors and actresses: Anthony Hopkins, Denzel Washington, Ellen Page, Meryl Streep, Mia Wasikowska and Robert DeNiro. Favorite books: Fyodor Mikhailovich Dostoyevsky, "The Karamazov Brothers", Shinran, "Lamentations of Divergences". Favorite phrase: Salvation by Faith. Twitter: @shibatau

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.