GOEDUHUB Online Courses || Last Batch Student's Projects || COVID-19 Projects(AI-ML) || Universities  ||  Placement Preparation  Subscribe our youtube channel
+91-7976731765 Free Online Tutorials ||  MACHINE LEARNING || NLP ||  OpenCV || Python || DBMS || OOPs || DSA || Java || Linux/Unix ||  C Programming
1 like 0 dislike
449 views
in Python Programming by Goeduhub's Expert (8k points)
Describe Concept of Python List
by (100 points)
Lists are very easy to use in python.

6 Answers

0 like 0 dislike
by Goeduhub's Expert (8k points)
 
Best answer

The Python List is a general data structure widely used in Python programs. They are found in other languages, often referred to as dynamic arrays. They are both mutable and a sequence data type that allows them to be indexed and sliced. The list can contain different types of objects, including other list objects.

List methods and supported operators

Starting with a given list a:
a = [1, 2, 3, 4, 5]
1. append(value) – appends a new element to the end of the list.
# Append values 6, 7, and 7 to the list

a.append(6)

a.append(7)
a.append(7)
# a: [1, 2, 3, 4, 5, 6, 7, 7]

# Append another list

b = [8, 9]
a.append(b)
# a: [1, 2, 3, 4, 5, 6, 7, 7, [8, 9]]

 # Append an element of a different type, as list elements do not need to have the same type

my_string = "hello world"
a.append(my_string)
# a: [1, 2, 3, 4, 5, 6, 7, 7, [8, 9], "hello world"]
Note that the append() method only appends one new element to the end of the list. If you append a list to another list, the list that you append becomes a single element at the end of the first list.

 # Appending a list to another list

a = [1, 2, 3, 4, 5, 6, 7, 7]
b = [8, 9]
a.append(b)
# a: [1, 2, 3, 4, 5, 6, 7, 7, [8, 9]]
a[8]
# Returns: [8,9]

2. extend(enumerable) – extends the list by appending elements from another enumerable 

a = [1, 2, 3, 4, 5, 6, 7, 7]

b = [8, 9, 10]


# Extend list by appending all elements from b

a.extend(b)

# a: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]


# Extend list with elements from a non-list enumerable:

a.extend(range(3))

# a: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10, 0, 1, 2]

Lists can also be concatenated with the + operator. Note that this does not modify any of the original lists:

a = [1, 2, 3, 4, 5, 6] + [7, 7] + b

# a: [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]

3. index(value, [startIndex]) – gets the index of the first occurrence of the input value. If the input value is not in the list a ValueError exception is raised. If a second argument is provided, the search is started at that specified index.

a.index(7)

# Returns: 6

a.index(49) # ValueError, because 49 is not in a.

a.index(7, 7)

# Returns: 7

a.index(7, 8) # ValueError, because there is no 7 starting at index 8

4. insert(index, value) – inserts value just before the specified index. Thus after the insertion the new element occupies position index.

a.insert(0, 0) # insert 0 at position 0

a.insert(2, 5) # insert 5 at position 2

# a: [0, 1, 5, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]

5. pop([index]) – removes and returns the item at index. With no argument it removes and returns the last element of the list.

a.pop(2)

# Returns: 5

# a: [0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]

a.pop(8)

# Returns: 7

# a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# With no argument:

a.pop()

# Returns: 10

# a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

6. remove(value) – removes the first occurrence of the specified value. If the provided value cannot be found, a ValueError is raised.

a.remove(0)

a.remove(9)

# a: [1, 2, 3, 4, 5, 6, 7, 8]

a.remove(10)

# ValueError, because 10 is not in a

7. reverse() – reverses the list in-place and returns None.

a.reverse()

# a: [8, 7, 6, 5, 4, 3, 2, 1]

There are also other ways of reversing a list.

8. count(value) – counts the number of occurrences of some value in the list.

a.count(7)

# Returns: 2

9. sort() – sorts the list in numerical and lexicographical order and returns None.

a.sort()

# a = [1, 2, 3, 4, 5, 6, 7, 8]

# Sorts the list in numerical order

Lists can also be reversed when sorted using the reverse=True flag in the sort() method.

a.sort(reverse=True)

# a = [8, 7, 6, 5, 4, 3, 2, 1]

If you want to sort by attributes of items, you can use the key keyword argument:

import datetime

class Person(object):

def __init__(self, name, birthday, height):

self.name = name

self.birthday = birthday

self.height = height

def __repr__(self):

return self.name

l = [Person("John Cena", datetime.date(1992, 9, 12), 175),

Person("Chuck Norris", datetime.date(1990, 8, 28), 180),

Person("Jon Skeet", datetime.date(1991, 7, 6), 185)]

l.sort(key=lambda item: item.name)

# l: [Chuck Norris, John Cena, Jon Skeet]

l.sort(key=lambda item: item.birthday)

# l: [Chuck Norris, Jon Skeet, John Cena]

l.sort(key=lambda item: item.height)

# l: [John Cena, Chuck Norris, Jon Skeet]

In case of list of dicts the concept is the same:

import datetime

l = [{'name':'John Cena', 'birthday': datetime.date(1992, 9, 12),'height': 175},

{'name': 'Chuck Norris', 'birthday': datetime.date(1990, 8, 28),'height': 180},

{'name': 'Jon Skeet', 'birthday': datetime.date(1991, 7, 6), 'height': 185}]

l.sort(key=lambda item: item['name'])

# l: [Chuck Norris, John Cena, Jon Skeet]

l.sort(key=lambda item: item['birthday'])

# l: [Chuck Norris, Jon Skeet, John Cena]

l.sort(key=lambda item: item['height'])

# l: [John Cena, Chuck Norris, Jon Skeet]

Sort by sub dict:

import datetime

l = [{'name':'John Cena', 'birthday': datetime.date(1992, 9, 12),'size': {'height': 175,

'weight': 100}},

{'name': 'Chuck Norris', 'birthday': datetime.date(1990, 8, 28),'size' : {'height': 180,

'weight': 90}},

{'name': 'Jon Skeet', 'birthday': datetime.date(1991, 7, 6), 'size': {'height': 185,

'weight': 110}}]

l.sort(key=lambda item: item['size']['height'])

# l: [John Cena, Chuck Norris, Jon Skeet]


Better way to sort using attrgetter and itemgetter

Lists can also be sorted using attrgetter and itemgetter functions from the operator module. These can help

improve readability and reusability. Here are some examples,

from operator import itemgetter,attrgetter

people = [{'name':'chandan','age':20,'salary':2000},

{'name':'chetan','age':18,'salary':5000},

{'name':'guru','age':30,'salary':3000}]

by_age = itemgetter('age')

by_salary = itemgetter('salary')

people.sort(key=by_age) #in-place sorting by age

people.sort(key=by_salary) #in-place sorting by salary

itemgetter can also be given an index. This is helpful if you want to sort based on indices of a tuple.

list_of_tuples = [(1,2), (3,4), (5,0)]

list_of_tuples.sort(key=itemgetter(1))

print(list_of_tuples) #[(5, 0), (1, 2), (3, 4)]

Use the attrgetter if you want to sort by attributes of an object,

persons = [Person("John Cena", datetime.date(1992, 9, 12), 175),

Person("Chuck Norris", datetime.date(1990, 8, 28), 180),

Person("Jon Skeet", datetime.date(1991, 7, 6), 185)] #reusing Person class from above

example

person.sort(key=attrgetter('name')) #sort by name

by_birthday = attrgetter('birthday')

person.sort(key=by_birthday) #sort by birthday

10. clear() – removes all items from the list

a.clear()

# a = []

11. Replication – multiplying an existing list by an integer will produce a larger list consisting of that many copies of the original. 

This can be useful for example for list initialization:

b = ["blah"] * 3

# b = ["blah", "blah", "blah"]

b = [1, 3, 5] * 5

# [1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5, 1, 3, 5]

Take care doing this if your list contains references to objects (eg a list of lists), see Common Pitfalls - List multiplication and common references.

12. Element deletion – it is possible to delete multiple elements in the list using the del keyword and slice notation:

a = list(range(10))

del a[::2]

# a = [1, 3, 5, 7, 9]

del a[-1]

# a = [1, 3, 5, 7]

del a[:]

# a = []

13. Copying

The default assignment "=" assigns a reference of the original list to the new name. That is, the original name

and new name are both pointing to the same list object. Changes made through any of them will be reflected in another. This is often not what you intended.

b = a

a.append(6)

# b: [1, 2, 3, 4, 5, 6]

If you want to create a copy of the list you have below options.

You can slice it:

new_list = old_list[:]

You can use the built in list() function:

new_list = list(old_list)

You can use generic copy.copy():

import copy

new_list = copy.copy(old_list) #inserts references to the objects found in the original.

This is a little slower than list() because it has to find out the datatype of old_list first.

If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

import copy

new_list = copy.deepcopy(old_list) #inserts copies of the objects found in the original.

Obviously the slowest and most memory-needing method, but sometimes unavoidable.

Python 3.x Version ≥ 3.0

copy() – Returns a shallow copy of the list

aa = a.copy()

# aa = [1, 2, 3, 4, 5]

by (101 points)
good content
by (422 points)
Supporting Operator is very well explain with individual example for each.
by (202 points)
mam, i have doubt in copying and sort.
can u give examples....
by (102 points)
Date 23/04/20
Topic:list
I learn about list how to insert ,append ,extend , delete and copy  of list  .
by (294 points)
In this module I have learnt about list also learnt about different operation performed on list like slicing and also learned how to use list
by (1.7k points)
@shagun doubt in copying and sort
you can understand from here-
Example of copying----

To actually copy the list, you have various possibilities:

1)You can use the builtin list.copy() method (available since Python 3.3):

new_list = old_list.copy()

2) You can slice it:
    new_list = old_list[:]

3)You can use the built in list() function:
new_list = list(old_list)

4)You can use generic copy.copy():

import copy
new_list = copy.copy(old_list)
by (471 points)
In this module  example (datetime) does not print the sort  value of name ,height and birthday .

# pycharm idle use
by (100 points)
In this article, i learned about python lists and different functions that can be used with a list in python like append, extend, coping a list Elements to another list, deleting or removing elements from lists etc.
by (279 points)
in this article we have learned about very good functionality of list.list provide very exciting function like append,extend,copy,remove etc . we use in our programming.
0 like 0 dislike
by (411 points)
Date: 22/04/2020

Topic: Python List

A LIST can be change. There are so many function which can be use to add, remove, delete, count, sort and insert the elements and by extend function we can add one list to another. I learned how to convert the string to LIST
0 like 0 dislike
by (182 points)

Module:-python list         Date:-24/04/2020

In this module I have learnt about list also learnt about different operation performed on list like slicing of list and many functions of list like append, insert, pop, remove and count .Here I also learnt how to extend a list by another list and how to append a list into another list and what is the difference between extend and append function.

Thank you !

0 like 0 dislike
by (135 points)
CONCEPT OF LIST

#empty list

my_list=[ ]

#list of integer

my_list =[1, 2, 3]

#list with mix  type

my_list =[1, 'hello', 3.4]
by (232 points)


                                                                                                                  Topic: Python List

Today i learn about python list ,A LIST can be change. There are so many function which can be use to add, remove, delete, count, sort and insert the elements and by extend function we can add one list to another. I learned how to convert the string to LIST

0 like 0 dislike
by (294 points)

In this article, i learned about python lists and different functions that can be used with a list in python like append, extend, coping a list Elements to another list, deleting or removing elements from lists etc.

0 like 0 dislike
by (294 points)
In this about I learned about python list

Related questions

0 like 0 dislike
4 answers 262 views
0 like 0 dislike
1 answer 29 views
1 like 0 dislike
1 answer 45 views
0 like 0 dislike
1 answer 31 views
0 like 0 dislike
1 answer 34 views
 Placements:   List of companies | Logical Reasoning Questions | Quantitative Aptitude Questions | General English Questions | Technical-MCQ and Interview Questions
 Important Lists: List of NITsList of IITsList of Exams After Graduation | List of Engineering Entrance Examinations (UG/PG)College ReviewsCollege Fest, Events & WorkshopsKnowledge ShareTrainees/Interns After 15-04-2020
Exams & Cutoffs: JEE Main | JEE Advanced | GATE | IES | ISROList of PSUs || Cutoff-GATECutoff_IIT-JEECS-ScopeECE ScopeEE-Scope
 Download Previous Year Papers For:  GATE | IES | RAJASTHAN TECHNICAL UNIVERSITY (RTU-Kota)RPSC Technical Exams | ISRO
 Goeduhub
About Us | Contact Us   Social::   |  | 
...