160 likes | 286 Vues
Lists in Python are integral for managing multiple variables of similar roles efficiently. Instead of declaring multiple individual variables, a list allows you to store related values under a single name, distinguished by their indices. This organizational structure simplifies data manipulation, enabling functions like appending values and iterating through elements. Whether it’s for temperature readings or scores, lists facilitate ease of data handling in Python. Discover how to create, reference, and manipulate lists, as well as generate random values for various applications.
E N D
Computer Science 101 Lists in Python
The need for lists • Often we need many different variables that play a similar role in the program • For example, suppose we have a temperature reading for each day of the year and need to manipulate these values several times within a program. • With simple variables, • We would need to use 365 variables. • We would not be able to loop over these variables.
Lists • A list is a numbered collection of variables. • The variables in a list share the same name and are distinguished from one another by their numbers or subscripts. • We can loop through the variables of a list by using a variable for the subscript. • The subscripts are always 0,1,…, size-1
temperature 75 82 68 58 67 79 70 65 63 61 temperature[4] Referencing List Elements • Suppose we have a list, temperature, for the temperature readings for the year. • The subscripts would be 0,1,…,364. • To refer to the reading for a given day, we use the name of the list with the subscript in brackets: temperature[4] for the fifth day.
Appending to a List • If we have a list, say scores, we can add a value, say num, to the list byscores.append(num)
Random numbers • For testing purposes or for simulations, it is convenient to let the computer generate random data for us. • In Python there is a library, random, that has a lot of tools for working with random numbers.
Randrange • random.randrange • random.randrange(num)gives a random number in range 0,…,(num-1) • random.randrange(num1,num2)gives random number in range num1,…,(num2-1)
Random Lists • To build a random list of values, we can • Start with an empty list, [] • Then append random values to the list
Is there easier way to loop the list?