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

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.

主站蜘蛛池模板: 宕昌县| 牙克石市| 平昌县| 望谟县| 新安县| 长葛市| 天长市| 行唐县| 名山县| 宿松县| 三穗县| 五寨县| 宁南县| 集安市| 兴城市| 濉溪县| 南川市| 古交市| 青田县| 桂林市| 鄂托克前旗| 承德县| 金湖县| 安徽省| 建德市| 安国市| 罗定市| 汕头市| 屯昌县| 涟源市| 蓝山县| 十堰市| 遂昌县| 鄂伦春自治旗| 衢州市| 马公市| 师宗县| 梁河县| 会理县| 洛浦县| 凌云县|