lists and iterations
what are lists?
lists can be used to store data can have duplicates and can have all data types
Tuple: collection that is ordered, unchangeable, allows duplicates\n”, Set: collection that is unordered, unchangeable, doesn’t allow duplicates\n”, Dictionary: collection that is ordered, changeable, doesn’t allow duplicates”
Method | Definition | Example | \n”, | |
” | - | - | - | \n”, |
” | append() | adds element to the end of the list | fruits.append("watermelon") | \n”, |
” | index() | returns the index of the first element with the specified value | fruits.index("apple") | \n”, |
” | insert() | adds element at given position | fruits.insert(1, "watermelon") | \n”, |
” | remove() | removes the first item with the specified value | fruits.remove("strawberry") | \n”, |
” | reverse() | reverses the list order | fruits.reverse() | \n”, |
” | sort() | sorts the list | fruits.sort() | \n”, |
” | count() | returns the amount of elements with the specified value | fruits.count("apple") | \n”, |
” | copy() | returns a copy of the list | fruits.copy() | \n”, |
” | clear() | removes the elements from the list | fruits.clear() | ” |
“cell_type”: “code”, “execution_count”: null, “metadata”: {}, “outputs”: [], “source”: [ “sports = ["football", "soccer", "baseball", "basketball"]\n”, “\n”, “# add "golf" as the 3rd element in the list\n”, insert(2, “golf”) “print (sports)”
”## Iteration\n”, “> Iteration is the repetition of a process or utterance applied to the result or taken from a previous statement.\n”, “> There’s a lot of types of iteration though, what to use? How do we apply iteration to lists? \n”, “> Lists, tuples, dictionaries, and sets are iterable objects. They are the ‘containers’ that store the data to iterate. \n”,
"# Using a for loop \n",
"list = [\"Alpha\", \"Bravo\", \"Charlie\", \"Delta\", \"Echo\", \"Foxtrot\", \"Golf\", \"Hotel\", \"India\", \"Juliett\", \"Kilo\", \"Lima\", \"Mike\", \"November\", \"Oscar\", \"Papa\", \"Quebec\", \"Romeo\", \"Sierra\", \"Tango\", \"Uniform\", \"Victor\", \"Whiskey\", \"X-ray\", \"Yankee\", \"Zulu\"]\n",
"\n",
"# using a for loop \n",
"for i in list:\n",
" #for item in the list, print the item \n",
" print(i)\n",
"# Using a for loop and range()\n",
"list = [\"Alpha\", \"Bravo\", \"Charlie\", \"Delta\", \"Echo\", \"Foxtrot\", \"Golf\", \"Hotel\", \"India\", \"Juliett\", \"Kilo\", \"Lima\", \"Mike\", \"November\", \"Oscar\", \"Papa\", \"Quebec\", \"Romeo\", \"Sierra\", \"Tango\", \"Uniform\", \"Victor\", \"Whiskey\", \"X-ray\", \"Yankee\", \"Zulu\"]\n",
"\n",
"# Taking the length of the list \n",
"lengthList = len(list) \n",
"\n",
"# Iteration using the amount of items in the list\n",
"for i in range(lengthList):\n",
" print(list[i])"