官术网_书友最值得收藏!

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:

List iteration

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.

主站蜘蛛池模板: 婺源县| 台南市| 天门市| 永福县| 蓝田县| 邯郸市| 惠安县| 和平县| 克拉玛依市| 皋兰县| 昌平区| 虹口区| 鄂托克旗| 将乐县| 肇源县| 巴彦淖尔市| 民和| 治多县| 合阳县| 昂仁县| 海口市| 南城县| 深州市| 行唐县| 大埔区| 永福县| 安徽省| 六枝特区| 湘潭市| 大城县| 潮州市| 郴州市| 新河县| 邵阳市| 雷山县| 新巴尔虎右旗| 山东| 莱州市| 新邵县| 渭源县| 海口市|