Python Lists
List
Lists are used to save more than one objects in a single variable.
Lists are one of four built-in statistics kinds in Python used to save collections of data, the different three are Tuple, Set, and Dictionary, all with distinct traits and usage.
Lists are created the usage of rectangular brackets:
Example:-
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List gadgets are ordered, changeable, and enable replica values.
List objects are indexed, the first object has index [0], the 2d object has index [1] etc.
Ordered
When we say that lists are ordered, it capacity that the objects have a described order, and that order will now not change.
If you add new objects to a list, the new gadgets will be positioned at the give up of the list.
Note: There are some listing strategies that will alternate the order, however in general: the order of the objects will no longer change.
Changeable
The listing is changeable, that means that we can change, add, and do away with gadgets in a listing after it has been created.
Allow Duplicates
Since lists are indexed, lists can have objects with the equal value:
Example:-
Lists permit reproduction values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To decide how many objects a listing has, use the len( ) function:
Example:-
Print the wide variety of objects in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Try it Yourself»»
List Items - Data Types
List gadgets can be of any facts type:
Example:-
String, int and boolean information types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Try it Yourself»»
A listing can incorporate special statistics types:
Example:-
A listing with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
type( )
From Python's perspective, lists are described as objects with the records kind 'list':Example:-
What is the statistics kind of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
The list( ) Constructor
It is additionally viable to use the list( ) constructor when developing a new list.
Example:-
Using the list( ) constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # notice the double round-brackets
print(thislist)
Try it Yourself»»
Python Collections (Arrays)
List is a series which is ordered and changeable. Allows replica members. Tuple is a series which is ordered and unchangeable. Allows replicamembers. Set is a series which is unordered and un-indexed. No reproduction members. Dictionary is a series which is ordered* and changeable. No replica members.
*As of Python model 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
When selecting a series type, it is beneficial to recognize the houses of that type. Choosing the proper kind for a precise facts set should suggest retention of meaning, and, it may want to suggest an expand in efficiency or security.
Python - Access List Items
Access Items
print(thislist[1])
Negative Indexing
Negative indexing skill begin from the end
print(thislist[-1])
Range of Indexes
print(thislist[2:5])
Note: The search will begin at index two (included) and cease at index 5 (not
included).
Remember that the first object has index 0.
By leaving out the begin value, the vary will begin at the first item:
Example:-
thislist = ["apple", "banana", "cherry",
"orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the cease value, the vary will go on to the stop of the list:
print(thislist[2:])
Range of Negative Indexes
print(thislist[-4:-1])
Check if Item Exists
To decide if a targeted object is existing in a listing use the in keyword:
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Python - Change List Items
Change Item Value
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Change a Range of Item Values
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
If you insert extra gadgets than you replace, the new objects will be inserted
the place you specified, and the last gadgets will cross accordingly:
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
Note: The size of the listing will exchange when the wide variety of objects
inserted does now not in shape the quantity of objects replaced.
thislist[1:3] = ["watermelon"]
print(thislist)
Insert Items
The insert( ) approach inserts an object at the precise index:
thislist.insert(2, "watermelon")
print(thislist)
Python - Add List Items
Append Items
thislist.append("orange")
print(thislist)
Insert Items
thislist.insert(1, "orange")
print(thislist)
Extend List
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
The factors will be brought to the give up of the list.
Add Any Iterable
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
Python - Remove List Items
Remove Specified Item
thislist.remove("banana")
print(thislist)
Remove Specified Index
thislist.pop(1)
print(thislist)
If you do now not specify the index, the pop( ) approach eliminates the final
item.
thislist.pop( )
print(thislist)
The del key-word additionally eliminates the designated index:
del thislist[0]
print(thislist)
The del key-word can additionally delete the listing completely.
del thislist
Clear the List
thislist.clear()
print(thislist)
Python - Loop Lists
Loop Through a List
for x in thislist:
print(x)
Loop Through the Index Numbers
for i in range(len(thislist)):
print(thislist[i])
The iterable created in the example above is [0, 1, 2].
Using a While Loop
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
Looping Using List Comprehension
[print(x) for x in thislist]
Python - List Comprehension
List Comprehension
newlist = [ ]
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With listing comprehension you can do all that with solely one line of code:
newlist = [x for x in fruits if "a" in x]
print(newlist)
The Syntax
Condition
The situation if x != "apple" will return True for all factors
different than "apple", making the new listing include all fruits
besides "apple".
Iterable
Same example, however with a condition:
Expression
The expression can additionally include conditions, now not like a filter,
however as a way to manipulate the outcome:
Python - Sort Lists
Sort List Alphanumerically
thislist.sort()
print(thislist)
Example:-
thislist.sort()
print(thislist)
Sort Descending
thislist.sort(reverse = True)
print(thislist)
Example:-
thislist.sort(reverse = True)
print(thislist)
Customize Sort Function
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
Case Insensitive Sort
thislist.sort()
print(thislist)
thislist.sort(key = str.lower)
print(thislist)
Reverse Order
thislist.reverse( )
print(thislist)
Python - Copy Lists
Copy a List
mylist = thislist.copy()
print(mylist)
Another way to make a replica is to use the built-in approach list( ).
mylist = list(thislist)
print(mylist)
Python - Join Lists
Join Two Lists
One of the best approaches are by way of the usage of the + operator.
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Another way to be part of two lists is with the aid of appending all the
gadgets from list2 into list1, one with the aid of one:
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Or you can use the extend( ) method, which reason is to add factors from one
listing to some other list:
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Python - List Methods
List Methods
Method Description
clear( ) Removes all the factors from the list.
copy( ) Returns a reproduction of the list.
count( ) Returns the quantity of factors with the distinctive value.
extend( ) Add the factors of a listing (or any iterable), to the give up of the present day list.
index( ) Returns the index of the first issue with the certain value.
insert( ) Adds an component at the detailed position.
pop( ) Removes the thing at the distinctive position.
reverse( ) Reverses the order of the list.
sort( ) Sorts the list.
0 Comments
If you are a good learner please leave a challenging question on comment box for us when you visited this website ( Coding with Fun).