Python List & Loops
Python Lists
Python has a great Data structure to store a bunch of value in a single variable is “List”. Like you might have studied in other programming languages there is an “Array”, similarly, there is list in python.
List literals are written within square brackets [ ].
Now, if you want to add more number into “my_list” than we can use “append()” function.
There are many useful functions in list, some of them are:
Wow, python:
Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.
FOR and IN loops:
“For” and “IN” is extremely useful in python. The for construct — for var in list — is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.
Range
The range(n) yields the number from 0,1,2. . . . ,n-1 and range(1,n) returns 1,2,3. . . . ,n-1 but not including the last number.
While Loop
Python also has the standard while-loop, and the break and continue statements work as in C++ and Java, altering the course of the innermost loop. The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers. There is the code to print even number between 0 to 10:
List Methods
Here are some common methods you can play with:
- list.append(elem) : adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
- list.insert(index, elem) : inserts the element at the given index, shifting elements to the right.
- list.extend(list2) : adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
- list.index(elem) : searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use “in” to check without a ValueError).
- list.remove(elem) : searches for the first instance of the given element and removes it (throws ValueError if not present)
- list.sort() — sorts the list in place (does not return it). (The sorted() function is preferred.)
- list.reverse() — reverses the list in place (does not return it)
- list.pop(index) — removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
So, that covers the basic of lists and loop.
So be connected. Thanks for visiting. Share this with your friends.
Comment your suggestions.
Leave a comment