How to Read in Multiple Values and Add Them to List Python
Storing Multiple Values in Lists
Overview
Teaching: xxx min
Exercises: 0 minQuestions
How tin can I store many values together?
Objectives
Explain what a list is.
Create and index lists of simple values.
Change the values of individual elements
Append values to an existing listing
Reorder and slice list elements
Create and manipulate nested lists
Merely as a for loop is a way to do operations many times, a list is a manner to store many values. Unlike NumPy arrays, lists are built into the language (then we don't take to load a library to employ them). Nosotros create a listing past putting values inside square brackets and separating the values with commas:
odds = [ 1 , 3 , 5 , seven ] impress ( 'odds are:' , odds ) We select individual elements from lists by indexing them:
print ( 'beginning and last:' , odds [ 0 ], odds [ - 1 ]) and if nosotros loop over a list, the loop variable is assigned elements one at a time:
for number in odds : print ( number ) In that location is i important difference between lists and strings: we tin alter the values in a list, but we cannot change individual characters in a string. For example:
names = [ 'Curie' , 'Darwing' , 'Turing' ] # typo in Darwin's name print ( 'names is originally:' , names ) names [ 1 ] = 'Darwin' # correct the name impress ( 'last value of names:' , names ) names is originally: ['Curie', 'Darwing', 'Turing'] final value of names: ['Curie', 'Darwin', 'Turing'] works, but:
name = 'Darwin' proper name [ 0 ] = 'd' --------------------------------------------------------------------------- TypeError Traceback (most contempo call last) <ipython-input-8-220df48aeb2e> in <module>() 1 proper noun = 'Darwin' ----> two name[0] = 'd' TypeError: 'str' object does non support item assignment does not.
Ch-Ch-Ch-Ch-Changes
Data which tin can be modified in place is called mutable, while data which cannot be modified is called immutable. Strings and numbers are immutable. This does not hateful that variables with string or number values are constants, but when nosotros want to change the value of a string or number variable, we tin just replace the erstwhile value with a completely new value.
Lists and arrays, on the other hand, are mutable: we can modify them later on they take been created. We tin alter individual elements, append new elements, or reorder the whole listing. For some operations, like sorting, we tin can choose whether to use a function that modifies the information in-place or a office that returns a modified copy and leaves the original unchanged.
Be conscientious when modifying data in-identify. If two variables refer to the same list, and you alter the list value, information technology will change for both variables!
salsa = [ 'peppers' , 'onions' , 'cilantro' , 'tomatoes' ] my_salsa = salsa # <-- my_salsa and salsa betoken to the *same* list data in memory salsa [ 0 ] = 'hot peppers' print ( 'Ingredients in my salsa:' , my_salsa )Ingredients in my salsa: ['hot peppers', 'onions', 'cilantro', 'tomatoes']If you want variables with mutable values to be independent, you must make a copy of the value when y'all assign it.
salsa = [ 'peppers' , 'onions' , 'cilantro' , 'tomatoes' ] my_salsa = list ( salsa ) # <-- makes a *copy* of the listing salsa [ 0 ] = 'hot peppers' impress ( 'Ingredients in my salsa:' , my_salsa )Ingredients in my salsa: ['peppers', 'onions', 'cilantro', 'tomatoes']Considering of pitfalls like this, code which modifies information in place can be more hard to understand. Nevertheless, it is often far more efficient to modify a large information structure in place than to create a modified re-create for every minor change. Yous should consider both of these aspects when writing your code.
Nested Lists
Since lists can contain any Python variable, it can even contain other lists.
For example, we could represent the products in the shelves of a small grocery shop:
x = [[ 'pepper' , 'zucchini' , 'onion' ], [ 'cabbage' , 'lettuce' , 'garlic' ], [ 'apple tree' , 'pear' , 'banana' ]]Here is a visual instance of how indexing a listing of lists
xworks:
![]()
Using the previously declared list
x, these would be the results of the index operations shown in the image:[['pepper', 'zucchini', 'onion']]['pepper', 'zucchini', 'onion']Thank you to Hadley Wickham for the image above.
Heterogeneous Lists
Lists in Python can contain elements of unlike types. Example:
sample_ages = [10, 12.5, 'Unknown']
There are many ways to modify the contents of lists besides assigning new values to individual elements:
odds . append ( 11 ) print ( 'odds after calculation a value:' , odds ) odds after calculation a value: [i, three, 5, vii, 11] del odds [ 0 ] print ( 'odds after removing the offset element:' , odds ) odds after removing the commencement element: [three, 5, seven, 11] odds . reverse () impress ( 'odds after reversing:' , odds ) odds later reversing: [eleven, seven, 5, 3] While modifying in place, it is useful to recall that Python treats lists in a slightly counter-intuitive manner.
If nosotros make a list and (effort to) re-create it then alter in identify, we tin can cause all sorts of trouble:
odds = [ 1 , 3 , 5 , seven ] primes = odds primes . append ( 2 ) print ( 'primes:' , primes ) impress ( 'odds:' , odds ) primes: [1, 3, 5, 7, 2] odds: [ane, 3, 5, 7, ii] This is because Python stores a list in memory, and then tin use multiple names to refer to the aforementioned list. If all we want to do is copy a (elementary) list, we tin use the list part, so we practise not modify a list nosotros did not mean to:
odds = [ 1 , 3 , 5 , 7 ] primes = list ( odds ) primes . append ( 2 ) impress ( 'primes:' , primes ) print ( 'odds:' , odds ) primes: [1, iii, 5, 7, ii] odds: [1, three, v, 7] This is different from how variables worked in lesson 1, and more similar to how a spreadsheet works.
Turn a String Into a List
Utilize a for-loop to convert the cord "howdy" into a list of letters:
[ "h" , "e" , "fifty" , "fifty" , "o" ]Hint: Yous can create an empty list similar this:
Solution
my_list = [] for char in "hello" : my_list . suspend ( char ) print ( my_list )
Subsets of lists and strings tin can exist accessed by specifying ranges of values in brackets, like to how we accessed ranges of positions in a NumPy array. This is normally referred to as "slicing" the list/string.
binomial_name = "Drosophila melanogaster" group = binomial_name [ 0 : ten ] impress ( "grouping:" , group ) species = binomial_name [ 11 : 24 ] print ( "species:" , species ) chromosomes = [ "X" , "Y" , "2" , "3" , "4" ] autosomes = chromosomes [ ii : v ] print ( "autosomes:" , autosomes ) last = chromosomes [ - one ] print ( "last:" , terminal ) grouping: Drosophila species: melanogaster autosomes: ["2", "3", "4"] last: 4 Slicing From the End
Use slicing to access only the final four characters of a string or entries of a listing.
string_for_slicing = "Observation date: 02-February-2013" list_for_slicing = [[ "fluorine" , "F" ], [ "chlorine" , "Cl" ], [ "bromine" , "Br" ], [ "iodine" , "I" ], [ "astatine" , "At" ]]"2013" [["chlorine", "Cl"], ["bromine", "Br"], ["iodine", "I"], ["astatine", "At"]]Would your solution work regardless of whether you knew beforehand the length of the string or list (e.g. if you wanted to apply the solution to a gear up of lists of unlike lengths)? If not, endeavour to alter your approach to make information technology more robust.
Solution
Utilise negative indices to count elements from the end of a container (such equally list or cord):
string_for_slicing [ - 4 :] list_for_slicing [ - 4 :]
Non-Continuous Slices
So far nosotros've seen how to use slicing to take unmarried blocks of successive entries from a sequence. Just what if we want to have a subset of entries that aren't side by side to each other in the sequence?
You can reach this by providing a third statement to the range inside the brackets, chosen the step size. The instance below shows how you lot tin can accept every third entry in a list:
primes = [ 2 , iii , 5 , seven , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 ] subset = primes [ 0 : 12 : 3 ] print ( "subset" , subset )Notice that the slice taken begins with the showtime entry in the range, followed by entries taken at equally-spaced intervals (the steps) thereafter. If you wanted to begin the subset with the third entry, you would need to specify that equally the starting bespeak of the sliced range:
primes = [ 2 , 3 , 5 , vii , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 ] subset = primes [ 2 : 12 : iii ] print ( "subset" , subset )Use the step size argument to create a new string that contains only every other grapheme in the string "In an octopus'southward garden in the shade"
beatles = "In an octopus'south garden in the shade"Solution
To obtain every other graphic symbol y'all need to provide a slice with the footstep size of 2:
You lot can too leave out the start and end of the slice to take the whole string and provide simply the step argument to go every second element:
If you lot want to have a slice from the beginning of a sequence, you tin omit the kickoff index in the range:
date = "Monday 4 January 2016" day = date [ 0 : 6 ] print ( "Using 0 to begin range:" , day ) mean solar day = engagement [: 6 ] print ( "Omitting showtime index:" , day ) Using 0 to begin range: Monday Omitting outset index: Monday And similarly, yous can omit the ending index in the range to take a slice to the very end of the sequence:
months = [ "january" , "feb" , "mar" , "apr" , "may" , "jun" , "jul" , "aug" , "sep" , "oct" , "nov" , "dec" ] sond = months [ 8 : 12 ] print ( "With known last position:" , sond ) sond = months [ 8 : len ( months )] print ( "Using len() to get final entry:" , sond ) sond = months [ 8 :] print ( "Omitting catastrophe alphabetize:" , sond ) With known final position: ["sep", "oct", "november", "december"] Using len() to get last entry: ["sep", "oct", "november", "dec"] Omitting catastrophe index: ["sep", "oct", "nov", "december"] Overloading
+unremarkably means add-on, only when used on strings or lists, it ways "concatenate". Given that, what practise you call back the multiplication operator*does on lists? In particular, what will exist the output of the following code?counts = [ ii , 4 , vi , 8 , 10 ] repeats = counts * ii print ( repeats )
[2, four, 6, 8, 10, 2, iv, half dozen, viii, 10][4, 8, 12, 16, 20][[2, 4, 6, viii, 10],[two, 4, 6, viii, x]][2, iv, half dozen, 8, 10, 4, viii, 12, 16, 20]The technical term for this is operator overloading: a single operator, like
+or*, tin can exercise different things depending on what information technology'southward applied to.Solution
The multiplication operator
*used on a list replicates elements of the list and concatenates them together:[2, 4, vi, 8, ten, two, 4, 6, 8, x]It's equivalent to:
Key Points
[value1, value2, value3, ...]creates a list.Lists can contain whatever Python object, including lists (i.e., listing of lists).
Lists are indexed and sliced with square brackets (e.g., list[0] and list[2:9]), in the same way equally strings and arrays.
Lists are mutable (i.e., their values can be inverse in place).
Strings are immutable (i.e., the characters in them cannot be changed).
Source: https://edcarp.github.io/2018-11-06-edinburgh-igmm-python/03-lists/index.html
Post a Comment for "How to Read in Multiple Values and Add Them to List Python"