Python List-generated

Source: Internet
Author: User

When we're going to generate the list, we can use the range function:

>>> Range (1,5) range (1, 5)

In the 3.0 version, the range is only used to generate an iterator (xrange is replaced).

But in the 2.0 version, we can use range to quickly generate a list

>>> Range (1, one) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> L = [] for in range (1,11):    * x)    >>> l[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The above code is a list that we generate

 for  in range (1,11) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But in the code below we use this fast list generator to save code.

Like a slice , our range function has more than two incoming values and can have three incoming values :

Print  for  in range (1,10,2)] [2, 12, 30, 56, 90]

The third pass-in value is the specified value of every two

In the List Builder, we can also append an if condition clause to the back.

def touppers (L):     return  for inch if isinstance (X,STR)] Print (Touppers (['hello','World', 101])) [ ' HELLO ' '  World ']

Isinstance (X,STR) can be used to determine if this is a string.

Upper () can be used to return uppercase letters.

For loops can be nested , so in a list build, you can also use a multi-layer for loop to generate the list.

Print  for inch  for inch  for inch if m*100+n*10+z = = z*100+n*10+m]) [101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 48  4, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 9 79, 989, 999]

Python List-generated

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.