- Learn Programming in Python with Cody Jackson
- Cody Jackson
- 304字
- 2021-06-10 19:06:09
List usage
Lists are most often used to store homogeneous values; that is, a list usually holds names, numbers, or other sequences that are all one data type. They don't have to; they can be used with whatever data types you want to mix and match. It's just usually easier to think of a list as holding a standard sequence of items.
The most common use of a list is to iterate over the list and perform the same action to each object within the list, hence the use of similar data types. This simple iteration is shown in the following screenshot:
Line 48 defines the list as a sequence of string values. Line 49 creates a for loop that iterates through the list, printing out a phrase for each item.
Lines 50 and 51 show alternative ways of iterating through and creating lists. This method is called list comprehension and is frequently found in code as a shortcut to writing a normal for loop to make a new list. Line 51 demonstrates that additional information can be provided to the returned values, much like the values returned in line 49.
One thing to note right now, however, is that you can use whatever word for the placeholder that you want; that is, if you wanted to use the name number instead of item in the preceding examples, you can do that. This is key because it was a weird concept for me when I first encountered it in Python. In other languages, loops like this are either hardwired into the language and you have to use its format or you have to expressly create the x value beforehand so you can call it in the loop. Python's way is much easier because you can use whatever name makes the most sense.
- 大學計算機基礎(第二版)
- Java程序設計(慕課版)
- Java EE 6 企業級應用開發教程
- Mastering JavaScript High Performance
- Spring Boot實戰
- Building Dynamics CRM 2015 Dashboards with Power BI
- Unity Character Animation with Mecanim
- Web Developer's Reference Guide
- 會當凌絕頂:Java開發修行實錄
- 你必須知道的.NET(第2版)
- 從零開始學UI設計·基礎篇
- R語言數據分析從入門到實戰
- MATLAB計算機視覺實戰
- Learning Android Application Development
- Python機器學習(原書第3版)