What Are Lists?
A list is a data structure in Python that is a mutable, ordered sequence of elements. Mutable means that you can change the items inside, while ordered sequence is in reference to index location. The first element in a list will always be located at index 0. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having different data types between square brackets [ ]. Also, like strings, each item within a list is assigned an index, or location, for where that item is saved in memory. Lists are also known as a data collection. Data collections are simply data types that can store multiple items. We’ll see other data collections, like dictionaries and tuples, in later chapters.
Declaring a List of Numbers
For our first list, we’re going to create a list filled with only numbers. Defining a list is like any other data type; on the left of the operator is the name of the variable, and on the right is the value. The difference here is that the value is a set of items declared between square brackets. This is useful for storing similar information, as you can easily pass around one variable name that stores several elements. To separate each item within a list, we simply use commas. Let’s try:
# declaring a list of numbers nums = [5, 10, 15.2, 20] print(nums)
ChApter 4 LIsts And Loops
Go ahead and run that cell. You’ll get an output of [5, 10, 15.2, 20]. When a list is output, it includes the brackets with it. This current list is made up of three integers and one float.
Accessing Elements Within a List
Now that we know how to define a list, we need to take the next step and understand how to access items within them. In order to access a specific element within a list, you use an index. When we declare our list variable, each item is given an index. Remember that indexing in Python starts at zero and is used with brackets. Wednesday of Week 2 also covers indexing:
# accessing elements within a list
print( nums[1] ) # will output the value at index 1 = 10 num = nums[2] # saves index value 2 into num print(num) # prints value assigned to num
Go ahead and run that cell. We’ll get two values output here, 10 and 15.2. The first value is output because we’re accessing the index location of 1 in our nums list, which has an integer of 10 stored there. The second value was printed out after we created a new variable called num, which was set to the value stored at index 2 within our nums
list.
Do'stlaringiz bilan baham: |