- 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.
- C++程序設(shè)計(jì)教程
- Designing Machine Learning Systems with Python
- TypeScript入門與實(shí)戰(zhàn)
- C語言程序設(shè)計(jì)
- PHP+MySQL+Dreamweaver動態(tài)網(wǎng)站開發(fā)實(shí)例教程
- Drupal 8 Module Development
- Mastering Linux Network Administration
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)實(shí)踐教程
- Linux C編程:一站式學(xué)習(xí)
- C++反匯編與逆向分析技術(shù)揭秘(第2版)
- Apache Camel Developer's Cookbook
- Oracle數(shù)據(jù)庫編程經(jīng)典300例
- HTML5+CSS3+jQuery Mobile APP與移動網(wǎng)站設(shè)計(jì)從入門到精通
- Hadoop大數(shù)據(jù)分析技術(shù)
- Django Design Patterns and Best Practices