My Coding >
Programming language >
Python LIST HowTo
Python LIST HowTo (Page: 1)
Go to Page:
List in Python is a traditional array with a lot of methods of managing it. Every cell of list can have it’s own type.
How to remove first element from list in Python
There are few different ways to remove first element from list in Python.
1. removing element with list.pop() function
Function pop(i) will remove element number i and return it. If this element is not present – function will rise an error: IndexError
2. removing element with del function
Function del(list[i]) will remove given element. If this element is not present – function will rise an error: IndexError
3. removing element with list.remove() function
Function list.remove(list[i]) will remove given element. If this element is not present – function will rise an error: IndexError
4. removing element with slicing
slices will produce new list with subset of elements. Making this list from second element and assigning this new list to our list will do remove first element
How to remove few element from list in Python
1. removing few element with del function
Function del(list[i:j]) will remove elements described in this slice. If some of those elements are not present – function will not do any action against absent elements
2. removing few element with slicing
Removing few elements with slicing is actually reverse task. We can leave untouched few elements with slicing.
So if you want to remove selected slice [1:4], you need to use concatenation of two parts
How to compare two lists
If you need to compare two lists in Python you have two different cases. What do you want to know – is the elements are the same in the list, or they are stored in the same order as well.
How to compare two lists for full identity
Use operator == to make full comparison of two lists
How to compare two lists for content only
If you are interesting to compare that two lists contains the same elements without comparing order, the easiest way is to compare sorted lists. Use operator == over the sorted() function
How to iterate over list in Python
Iteration with range(len())
Traditional way for iterate through the list with indexes is to use range(len()) set of functions.
Iteration over values in the list
For most of the common tasks it is easier to iterate over the values of the list. Yuo should understand, that val is a shallow copy of the value. Modification of val will not make any impact on the original list
Iteration with enumerate()
enumerate() is a very convenient build-in function, also preferable to iterate over the list in Python.
Last 10 artitles
9 popular artitles
|© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.|